How do you read from stdin in Python?

0 votes
asked Sep 20, 2009 by tehryan

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?

15 Answers

0 votes
answered Sep 20, 2009 by mark-rushakoff

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.

0 votes
answered Sep 20, 2010 by user303110
import sys

for line in sys.stdin:
    print line
0 votes
answered Sep 3, 2011 by pat-notz

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
0 votes
answered Sep 30, 2011 by massimiliano-torrome

The answer proposed by others:

for line in sys.stdin:
  print line

is very simple and pythonic, but it must be noted that the script will wait until EOF before starting to iterate on the lines of input.

This means that tail -f error_log | myscript.py will not process lines as expected.

The correct script for such a use case would be:

while 1:
    try:
        line = sys.stdin.readline()
    except KeyboardInterrupt:
        break

    if not line:
        break

    print line

UPDATE
From the comments it has been cleared that on python 2 only there might be buffering involved, so that you end up waiting for the buffer to fill or EOF before the print call is issued.

0 votes
answered Sep 9, 2012 by rlib

This will echo standard input to standard output:

import sys
line = sys.stdin.readline()
while line:
    print line,
    line = sys.stdin.readline()
0 votes
answered Sep 27, 2013 by boubakr

Try this:

import sys

print sys.stdin.read().upper()

and check it with:

$ echo "Hello World" | python myFile.py
0 votes
answered Sep 29, 2013 by emil-lundberg

Building on all the anwers using sys.stdin, you can also do something like the following to read from an argument file if at least one argument exists, and fall back to stdin otherwise:

import sys
f = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin    
for line in f:
#     Do your stuff

and use it as either

$ python do-my-stuff.py infile.txt

or

$ cat infile.txt | python do-my-stuff.py

or even

$ python do-my-stuff.py < infile.txt

That would make your Python script behave like many GNU/Unix programs such as cat, grep and sed.

0 votes
answered Sep 20, 2014 by wei

You can read from stdin and then store inputs into "data" as follows:

data = ""
for line in sys.stdin:
    data += line
0 votes
answered Sep 29, 2014 by estani

I had some issues when getting this to work for reading over sockets piped to it. When the socket got closed it started returning empty string in an active loop. So this is my solution to it (which I only tested in linux, but hope it works in all other systems)

import sys, os
sep=os.linesep

while sep == os.linesep:
    data = sys.stdin.readline()               
    sep = data[-len(os.linesep):]
    print '> "%s"' % data.strip()

So if you start listening on a socket it will work properly (e.g. in bash):

while :; do nc -l 12345 | python test.py ; done

And you can call it with telnet or just point a browser to localhost:12345

0 votes
answered Sep 7, 2016 by uri-goren

I am pretty amazed no one had mentioned this hack so far:

python -c "import sys;print (''.join([l for l in sys.stdin.readlines()]))"

compatible with both python2 and python3

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...