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


当前回答

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

e.g.

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

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

其他回答

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

例如

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

or

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

for line in sys.stdin:
    print(line)

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

其他人提出的答案:

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。

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

argparse是一个简单的解决方案

与Python版本2和3兼容的示例:

#!/usr/bin/python

import argparse
import sys

parser = argparse.ArgumentParser()

parser.add_argument('infile',
                    default=sys.stdin,
                    type=argparse.FileType('r'),
                    nargs='?')

args = parser.parse_args()

data = args.infile.read()

您可以通过多种方式运行此脚本:

1.使用stdin

echo 'foo bar' | ./above-script.py

  或更短,方法是将echo替换为here字符串:

./above-script.py <<< 'foo bar'

2.使用文件名参数

echo 'foo bar' > my-file.data
./above-script.py my-file.data

3.通过特殊文件名使用stdin-

echo 'foo bar' | ./above-script.py -