如何读取stdin?一些代码高尔夫挑战需要使用stdin进行输入。


当前回答

对于Python 3,这将是:

# Filename e.g. cat.py
import sys

for line in sys.stdin:
    print(line, end="")

这基本上是cat(1)的一种简单形式,因为它没有在每行后面添加一个换行符。您可以使用这个(在您使用chmod+x cat.py标记文件可执行文件之后),例如:

echo Hello | ./cat.py

其他回答

Python还具有内置函数input()和raw_input()。请参阅内置函数下的Python文档。

例如

name = raw_input("Enter your name: ")   # Python 2.x

or

name = input("Enter your name: ")   # Python 3

非阻塞、字节模式、stdin->stdout:

# pipe.py

import os, sys, time

os.set_blocking(0, False)
sys.stdin = os.fdopen(0, 'rb', 0)
sys.stdout = os.fdopen(1, 'wb', 0)

while 1:
    time.sleep(.1)
    try: out = sys.stdin.read()
    except:
        sys.stdout.write(b"E")
        continue
    if out is None:
        sys.stdout.write(b"N")
        continue
    if not out:
        sys.stdout.write(b"_")
        break
    # working..
    out = b"<" + out + b">"
    sys.stdout.write(out)

sys.stdout.write(b".\n")

用法:

$ for i in 1 2 3; do sleep 1; printf "===$i==="; done | python3 pipe.py
NNNNNNNNN<===1===>NNNNNNNNN<===2===>NNNNNNNNN<===3===>_.

最小代码:

import os, sys

os.set_blocking(0, False)
fd0 = os.fdopen(0, 'rb', 0)
fd1 = os.fdopen(1, 'wb', 0)

while 1:
    bl = fd0.read()
    if bl is None: continue
    if not bl: break
    fd1.write(bl)

在Linux、Python 3.9.2上测试

我在读取通过管道连接到它的套接字时遇到了一些问题。当套接字关闭时,它开始在活动循环中返回空字符串。所以这是我的解决方案(我只在linux中测试过,但希望它能在所有其他系统中运行)

import sys, os
sep=os.linesep

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

因此,如果您开始监听套接字,它将正常工作(例如在bash中):

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

您可以使用telnet调用它,也可以将浏览器指向localhost:1245

有os.读取(0,x)它从表示stdin的0读取xbytes。这是一个无缓冲的读取,比sys.stdin.read()更低级

以下代码片段将帮助您(它将把所有stdin块读取到EOF,并将其转换为一个字符串):

import sys
input_str = sys.stdin.read()
print input_str.split()