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


当前回答

当使用-c命令时,作为一种巧妙的方法,您可以将shell脚本命令放在以$符号开头的括号内的引号中,而不是读取stdin(在某些情况下更灵活)。

e.g.

python3 -c "import sys; print(len(sys.argv[1].split('\n')))" "$(cat ~/.goldendict/history)"

这将统计goldendict历史文件中的行数。

其他回答

我非常惊讶,到目前为止没有人提到过这个黑客:

python -c "import sys; set(map(sys.stdout.write,sys.stdin))"

在python2中,您可以放弃set()调用,但这两种方法都可以

从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()

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

例如

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

or

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

其他人提出的答案:

for line in sys.stdin:
  print line

是非常简单和Python化的,但必须注意的是,脚本将等待EOF,然后开始迭代输入行。

这意味着tail-f error_log | myscript.py不会按预期处理行。

这种用例的正确脚本是:

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

    if not line:
        break

    print line

更新从评论中可以看出,在python2上可能只涉及缓冲区,因此在发出打印调用之前,您最终会等待缓冲区填充或EOF。

关于此:

对于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