How do you read from stdin?
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?
You could use the fileinput
module:
import fileinput
for line in fileinput.input():
pass
fileinput
will loop through all the lines in the input specified as file names given in command-line arguments, or the standard input if no arguments are provided.
Note: line
will contain a trailing newline; to remove it use line.rstrip()
There's a few ways to do it.
sys.stdin
is a file-like object on which you can call functionsread
orreadlines
if you want to read everything or you want to read everything and split it by newline automatically. (You need toimport sys
for this to work.)If you want to prompt the user for input, you can use
raw_input
in Python 2.X, and justinput
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.
import sys
for line in sys.stdin:
print(line)
Note that this will include a newline character at the end. To remove the newline at the end, use line.rstrip()
as @brittohalloran said.
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