如何读取stdin?一些代码高尔夫挑战需要使用stdin进行输入。
当前回答
Python还具有内置函数input()和raw_input()。请参阅内置函数下的Python文档。
例如
name = raw_input("Enter your name: ") # Python 2.x
or
name = input("Enter your name: ") # Python 3
其他回答
使用文件输入模块:
import fileinput
for line in fileinput.input():
pass
fileinput将循环通过输入中指定为命令行参数中给定的文件名的所有行,如果没有提供参数,则循环通过标准输入。
注意:行将包含尾随换行符;要删除它,请使用line.rstrip()。
我非常惊讶,到目前为止没有人提到过这个黑客:
python -c "import sys; set(map(sys.stdout.write,sys.stdin))"
在python2中,您可以放弃set()调用,但这两种方法都可以
我对解决方案的问题
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)
对于Python 3,这将是:
# Filename e.g. cat.py
import sys
for line in sys.stdin:
print(line, end="")
这基本上是cat(1)的一种简单形式,因为它没有在每行后面添加一个换行符。您可以使用这个(在您使用chmod+x cat.py标记文件可执行文件之后),例如:
echo Hello | ./cat.py
Python还具有内置函数input()和raw_input()。请参阅内置函数下的Python文档。
例如
name = raw_input("Enter your name: ") # Python 2.x
or
name = input("Enter your name: ") # Python 3
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录