How do you read from stdin in Python?

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?

share edit
 
 
The answers below generally point either to raw_input() or sys.stdin (and the latter seems more appropriate) but there are subtle differences between the two that I thought the following post covered pretty well: albertech.blogspot.com/2015/02/…  –    jar   Feb 27 at 3:46

13 Answers

This is something I learned from Stack Overflow:

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.

share edit
 
25 
14 
This is what you want (albeit not what you asked for). Users can pass data to your application by either argument format.py addresses.txt or standard input cat addresses.txt | format.py. This makes your app more usable (note that grep and the rest of Unix can be used either way)  –    Colonel Panic Aug 14 '12 at 10:18  
7 
So this is the Python equivalent of Perl's while(<>) ?  –    Kyle Strand   May 8 '13 at 23:05
7 
@Val You are using the wrong tool, this allows you to read a bunch of lines which can then be terminated with EOF (Ctrl + D). To read a single line ("prompt"), see the other answer.  –    Lekensteyn   Oct 2 '13 at 21:13
7 
How does this coexist with argparse?  –    Nick T   Aug 28 '14 at 0:14

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 inputin Python 3.

  • If you actually just want to read command-line options, you can access them via the sys.argvlist.

You will probably find this Wikibook article on I/O in Python to be a useful reference as well.

share edit
 
2 
the prompting is optional  –    newacct   Sep 20 '09 at 7:51
13 
The prompt (waiting for user input) isn't optional, but displaying prompt text is.  –    2rs2ts   Dec 7 '11 at 9:03
 
I like this solution. I transferred from python 2.7.5 to python 3.4 and was wondering why raw_input wasn't working  –    corvid   Mar 29 '14 at 20:22
import sys

for line in sys.stdin:
    print line
share edit
 
1 
I'm having this problem in Python 3.2 for file in sys.stdin: TypeError: 'NoneType' object is not iterable  –    Jader Dias   Jun 14 '11 at 13:02
2 
input_text = "".join(sys.stdin)  –    m.kocikowski   Mar 21 '13 at 18:20
1 
@JaderDias It works for me (Python 3.2.3, 3.3.2). Are you sure that you have not accidentally closed stdin of the Python process?  –    Lekensteyn   Oct 2 '13 at 21:19
 
Just remember that if you do that in an interactive interpreter, it will never come out of the loop; whenever you type something during that loop, it will basically return what you printed. Go ahead and try it out!  –    Zizouz212 Feb 18 at 22:38

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.
share edit
 
2 
I'm having this problem with the first two lines in Python 3.2 ` data = sys.stdin.readlines() AttributeError: 'NoneType' object has no attribute 'readlines'`  –    Jader Dias   Jun 14 '11 at 13:00  
1 
Here's a more memory efficient (and maybe faster) way to count lines in Python:print(sum(chunk.count('\n') for chunk in iter(partial(sys.stdin.read, 1 << 15), ''))).see wc-l.py  –    J.F. Sebastian   Nov 16 '12 at 4:32

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
share edit
 

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.

share edit
 
5 
Are you sure? I'm running this with 3.2.2 and each line is echoed as I type.  –    Graham Lea   Oct 27 '11 at 9:49
1 
I just tried it again and it indeed seems to work correctly. Not sure if it was a bug in my python interpreter or what but I'm fairly sure that it did not work before. Thanks for bringing this up!  –    Massimiliano Torromeo   Oct 27 '11 at 10:22
 
The for line in sys.stdin: pattern does not wait for EOF. But if you test on very small files, responses may get buffered. Test with more data to see that it reads intermediate results.  –    mb.   Jul 11 '12 at 2:06  
 
I get wait for End Of File or buffering, when taking input from a stream when using python 2.6.6, but with 3.1.3 I don't. Note print line does not woke in 3.1.3, but print(line) does.  –    richard   Sep 7 '12 at 9:41
1 
I suspect this is related to detection of tty in libc, so when you pipe it detects on a interactive shell it detects none tty, unbuffer from expect-dev is a handy util that I believe injects a shim via ld_preload so is_atty returns true (I suspect that's how it is handing it)  –    Matt Freeman   Mar 12 at 8:16  

This will echo standard input to standard output:

import sys
line = sys.stdin.readline()
while line:
    print line,
    line = sys.stdin.readline()
share edit
 

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 = sys.stdin
if len(sys.argv) > 1:
    f = open(sys.argv[1])

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 catgrepand sed.

share edit
 

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

data = ""
for line in sys.stdin:
    data += line
share edit
 

Try this:

import sys

print sys.stdin.read().upper()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值