如何读取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
其他回答
以下代码片段将帮助您(它将把所有stdin块读取到EOF,并将其转换为一个字符串):
import sys
input_str = sys.stdin.read()
print input_str.split()
我在读取通过管道连接到它的套接字时遇到了一些问题。当套接字关闭时,它开始在活动循环中返回空字符串。所以这是我的解决方案(我只在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
当使用-c命令时,作为一种巧妙的方法,您可以将shell脚本命令放在以$符号开头的括号内的引号中,而不是读取stdin(在某些情况下更灵活)。
e.g.
python3 -c "import sys; print(len(sys.argv[1].split('\n')))" "$(cat ~/.goldendict/history)"
这将统计goldendict历史文件中的行数。
使用文件输入模块:
import fileinput
for line in fileinput.input():
pass
fileinput将循环通过输入中指定为命令行参数中给定的文件名的所有行,如果没有提供参数,则循环通过标准输入。
注意:行将包含尾随换行符;要删除它,请使用line.rstrip()。
以下是学习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中获得所有直接子目录