如何读取stdin?一些代码高尔夫挑战需要使用stdin进行输入。
当前回答
在使用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。
其他回答
我在读取通过管道连接到它的套接字时遇到了一些问题。当套接字关闭时,它开始在活动循环中返回空字符串。所以这是我的解决方案(我只在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
其他人提出的答案:
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。
从Python 3.8开始,您可以使用赋值表达式:
while (line := input()):
print(line)
我对解决方案的问题
import sys
for line in sys.stdin:
print(line)
如果不向stdin传递任何数据,它将永远阻塞。这就是为什么我喜欢这个答案:首先检查stdin上是否有一些数据,然后读取它
import sys
import select
# select(files to read from, files to write to, magic, timeout)
# timeout=0.0 is essential b/c we want to know the asnwer right away
if select.select([sys.stdin], [], [], 0.0)[0]:
help_file_fragment = sys.stdin.read()
else:
print("No data passed to stdin", file=sys.stderr)
sys.exit(2)
在使用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。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录