如何读取stdin?一些代码高尔夫挑战需要使用stdin进行输入。
当前回答
以下是学习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.
其他回答
使用文件输入模块:
import fileinput
for line in fileinput.input():
pass
fileinput将循环通过输入中指定为命令行参数中给定的文件名的所有行,如果没有提供参数,则循环通过标准输入。
注意:行将包含尾随换行符;要删除它,请使用line.rstrip()。
关于此:
对于sys.stdin中的行:
我只是在python2.7上尝试了它(按照其他人的建议),用于一个非常大的文件,我不推荐它,正是出于上述原因(很长一段时间没有发生任何事情)。
我最终得到了一个稍微更像蟒蛇的解决方案(它适用于更大的文件):
with open(sys.argv[1], 'r') as f:
for line in f:
然后我可以在本地运行脚本:
python myscript.py "0 1 2 3 4..." # can be a multi-line string or filename - any std.in input will work
从Python 3.8开始,您可以使用赋值表达式:
while (line := input()):
print(line)
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)
如果不向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)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录