在打算从 shell 运行的简单 Python 脚本中,我能否可靠地确定 sys.stdin 是从实际文件重定向还是从另一个进程通过管道传输?
我想根据标准输入是来自数据文件还是通过管道从另一个进程流式传输来更改运行时行为。
正如预期的那样,
isatty()
在这两种情况下都返回 False。这是一个快速 isatty()
测试:
# test.py
import os
import sys
print sys.stdin.isatty()
print os.isatty(sys.stdin.fileno())
测试:
python test.py < file.txt
产生:
False
False
和:
ls -al | python test.py
产生:
False
False
有这样做的Pythonic方法吗?
特定于 Unix/Linux 没问题,不过如果能知道是否可以以可移植的方式做到这一点就好了。
编辑:回复评论者的注释:我为什么关心?好吧,就我而言,我想处理从另一个进程通过管道传输时以不规则间隔传入的带时间戳的数据;当我播放文件中预先录制的数据时,我想使用固定或可变延迟来重播它。
我同意使用更干净的方法可能是有利的(我可以想到几种方法,包括在播放流中插入延迟的中间脚本),但我非常好奇。
stat
宏:
import os, stat
mode = os.fstat(0).st_mode
if stat.S_ISFIFO(mode):
print("stdin is piped")
elif stat.S_ISREG(mode):
print("stdin is redirected")
else:
print("stdin is terminal")