Python 如何检查 stdin 是否有一些数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3762881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check if stdin has some data?
提问by mlzboy
In Python, how do you check if sys.stdinhas data or not?
在 Python 中,如何检查是否sys.stdin有数据?
I found that os.isatty(0)can not only check if stdin is connected to a TTY device, but also if there is data available.
我发现这os.isatty(0)不仅可以检查 stdin 是否连接到 TTY 设备,还可以检查是否有可用数据。
But if someone uses code such as
但是如果有人使用诸如
sys.stdin = cStringIO.StringIO("ddd")
and after that uses os.isatty(0), it still returns True. What do I need to do to check if stdin has data?
在使用之后os.isatty(0),它仍然返回 True。我需要做什么来检查 stdin 是否有数据?
采纳答案by Rakis
On Unix systems you can do the following:
在 Unix 系统上,您可以执行以下操作:
import sys
import select
if select.select([sys.stdin,],[],[],0.0)[0]:
print "Have data!"
else:
print "No data"
On Windows the select module may only be used with sockets though so you'd need to use an alternative mechanism.
在 Windows 上, select 模块只能与套接字一起使用,因此您需要使用替代机制。
回答by Gregg Lind
Depending on the goal here:
取决于这里的目标:
import fileinput
for line in fileinput.input():
do_something(line)
can also be useful.
也很有用。
回答by Erin
I've been using
我一直在用
if not sys.stdin.isatty()
Here's an example:
下面是一个例子:
import sys
def main():
if not sys.stdin.isatty():
print "not sys.stdin.isatty"
else:
print "is sys.stdin.isatty"
Running
跑步
$ echo "asdf" | stdin.py
not sys.stdin.isatty
sys.stdin.isatty()returns false if there's something in stdin.
sys.stdin.isatty()如果stdin.
isatty(...)
isatty() -> true or false. True if the file is connected to a tty device.
回答by n.caillou
(edit: This answers a related question that has since been merged here.)
(编辑:这回答了一个相关问题,该问题已在此处合并。)
As mentioned by others, there's no foolproof way to know if data will become available from stdin, because UNIX doesn't allow it (and more generally because it can't guess the future behavior of whatever program stdin connects to).
正如其他人所提到的,没有万无一失的方法可以知道数据是否可以从 stdin 获得,因为 UNIX 不允许这样做(更普遍的是因为它无法猜测 stdin 连接到的任何程序的未来行为)。
Always wait for stdin, even if there may be nothing (that's what grepetc. do), or ask the user for a -argument.
始终等待 stdin,即使可能什么都没有(这就是grep等),或者向用户询问-参数。
回答by hsyn
Using built in modules this can be achieved with following code as Greg gave already the idea:
使用内置模块,这可以通过以下代码实现,因为 Greg 已经给出了这个想法:
import fileinput
isStdin = True
for line in fileinput.input:
# check if it is not stdin
if not fileinput.isstdin():
isStdin = False
break
# continue to read stdin
print(line)
fileinput.close()

