tags:

views:

16579

answers:

4

I'm trying to do some of the code golf challenges but they all require the input to be taken from stdin and I don't know how to get that in python.

+13  A: 

Here's from Learning Python:

import sys
data = sys.stdin.readlines()
print "Counted", len(data), "lines."

On Unix, you could test it by doing something like:

% cat countlines.py | python countlines.py 
Counted 3 lines.

On Windows or DOS, you'd do:

C:\> type countlines.py | python countlines.py 
Counted 3 lines.
eed3si9n
+25  A: 

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.

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.

Mark Rushakoff
the prompting is optional
newacct
+13  A: 

This is something I learnt from StackOverflow

import fileinput

for line in fileinput.input():
    pass

Fileinput will run over all lines in the input; it takes the files given as command-line arguments, or if missing, the standard input.

kaizer.se
Thanks for that one, I didn't know it.
e-satis
+4  A: 
import sys

for line in sys.stdin:
    print line