I\'m trying to do some of the code golf challenges, but they all require the input to be taken from stdin
. How do I get that in Python?
Read from sys.stdin
, but to read binary data on Windows, you need to be extra careful, because sys.stdin
there is opened in text mode and it will corrupt \r\n
replacing them with \n
.
The solution is to set mode to binary if Windows + Python 2 is detected, and on Python 3 use sys.stdin.buffer
.
import sys
PY3K = sys.version_info >= (3, 0)
if PY3K:
source = sys.stdin.buffer
else:
# Python 2 on Windows opens sys.stdin in text mode, and
# binary data that read from it becomes corrupted on \r\n
if sys.platform == "win32":
# set sys.stdin to binary mode
import os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
source = sys.stdin
b = source.read()
There's a few ways to do it.
sys.stdin is a file-like object on which you can call functions read
or readlines
if you want to read everything or you want to read everything and split it by newline automatically. (You need to import sys
for this to work.)
If you want to prompt the user for input, you can use raw_input in Python 2.X, and just input in Python 3.
If you actually just want to read command-line options, you can access them via the sys.argv list.
You will probably find this Wikibook article on I/O in Python to be a useful reference as well.
For Python 3 that would be:
# Filename e.g. cat.py
import sys
for line in sys.stdin:
print(line, end="")
This is basically a simple form of cat(1), since it doesn't add a newline after each line. You can use this (after You marked the file executable using chmod +x cat.py
such as:
echo Hello | ./cat.py
Python also has built-in functions input()
and raw_input()
. See the Python documentation under Built-in Functions.
For example,
name = raw_input("Enter your name: ") # Python 2.x
or
name = input("Enter your name: ") # Python 3
The following chip of code will help you (it will read all of stdin blocking unto EOF
, into one string):
import sys
input_str = sys.stdin.read()
print input_str.split()
When using -c
command, as a tricky way, instead of reading the stdin
(and more flexible in some cases) you can pass a shell script command as well to your python command by putting the shell command in quotes within a parenthesis started by $
sign.
e.g.
python3 -c "import sys; print(len(sys.argv[1].split('\n')))" "$(cat ~/.goldendict/history)"
This will count the number of lines from goldendict's history file.