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


当前回答

从Python 3.8开始,您可以使用赋值表达式:

while (line := input()):
    print(line)

其他回答

import sys

for line in sys.stdin:
    print(line)

请注意,这将在末尾包含一个换行符。要删除末尾的换行符,请使用@brittohaloran所说的line.rstrip()。

关于此:

对于sys.stdin中的行:

我只是在python2.7上尝试了它(按照其他人的建议),用于一个非常大的文件,我不推荐它,正是出于上述原因(很长一段时间没有发生任何事情)。

我最终得到了一个稍微更像蟒蛇的解决方案(它适用于更大的文件):

with open(sys.argv[1], 'r') as f:
    for line in f:

然后我可以在本地运行脚本:

python myscript.py "0 1 2 3 4..." # can be a multi-line string or filename - any std.in input will work

使用文件输入模块:

import fileinput

for line in fileinput.input():
    pass

fileinput将循环通过输入中指定为命令行参数中给定的文件名的所有行,如果没有提供参数,则循环通过标准输入。

注意:行将包含尾随换行符;要删除它,请使用line.rstrip()。

从Python 3.8开始,您可以使用赋值表达式:

while (line := input()):
    print(line)

从sys.stdin读取,但要在Windows上读取二进制数据,您需要格外小心,因为sys.stdn是以文本模式打开的,它会损坏\r\n将其替换为\n。

解决方案是,如果检测到Windows+Python2,则将模式设置为二进制,在Python3上使用sys.stdin.buffer。

import sys

PY3K = sys.version_info >= (3, 0)

if PY3K:
    source = sys.stdin.buffer
else:
    # Python 2 on Windows opens sys.stdin in text mode, and
    # binary data that read from it becomes corrupted on \r\n
    if sys.platform == "win32":
        # set sys.stdin to binary mode
        import os, msvcrt
        msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
    source = sys.stdin

b = source.read()