如何读取stdin?一些代码高尔夫挑战需要使用stdin进行输入。
当前回答
我在读取通过管道连接到它的套接字时遇到了一些问题。当套接字关闭时,它开始在活动循环中返回空字符串。所以这是我的解决方案(我只在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
其他回答
import sys
for line in sys.stdin:
print(line)
请注意,这将在末尾包含一个换行符。要删除末尾的换行符,请使用@brittohaloran所说的line.rstrip()。
在使用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。
有os.读取(0,x)它从表示stdin的0读取xbytes。这是一个无缓冲的读取,比sys.stdin.read()更低级
使用文件输入模块:
import fileinput
for line in fileinput.input():
pass
fileinput将循环通过输入中指定为命令行参数中给定的文件名的所有行,如果没有提供参数,则循环通过标准输入。
注意:行将包含尾随换行符;要删除它,请使用line.rstrip()。
我非常惊讶,到目前为止没有人提到过这个黑客:
python -c "import sys; set(map(sys.stdout.write,sys.stdin))"
在python2中,您可以放弃set()调用,但这两种方法都可以
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录