如何读取stdin?一些代码高尔夫挑战需要使用stdin进行输入。
当前回答
有os.读取(0,x)它从表示stdin的0读取xbytes。这是一个无缓冲的读取,比sys.stdin.read()更低级
其他回答
其他人提出的答案:
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。
这将使标准输入与标准输出相呼应:
import sys
line = sys.stdin.readline()
while line:
print line,
line = sys.stdin.readline()
在使用sys.stdin构建所有函数的基础上,如果至少存在一个参数,还可以执行以下操作来读取参数文件,否则返回到stdin:
import sys
f = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
for line in f:
# Do your stuff
并将其用作
$ python do-my-stuff.py infile.txt
or
$ cat infile.txt | python do-my-stuff.py
甚至
$ python do-my-stuff.py < infile.txt
这将使您的Python脚本表现得像许多GNU/Unix程序,如cat、grep和sed。
当使用-c命令时,作为一种巧妙的方法,您可以将shell脚本命令放在以$符号开头的括号内的引号中,而不是读取stdin(在某些情况下更灵活)。
e.g.
python3 -c "import sys; print(len(sys.argv[1].split('\n')))" "$(cat ~/.goldendict/history)"
这将统计goldendict历史文件中的行数。
以下是学习Python的内容:
import sys
data = sys.stdin.readlines()
print "Counted", len(data), "lines."
在Unix上,您可以通过以下方式进行测试:
% cat countlines.py | python countlines.py
Counted 3 lines.
在Windows或DOS上,您可以执行以下操作:
C:\> type countlines.py | python countlines.py
Counted 3 lines.
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录