3
是否有某种方法来检查python进程的输出是否正在写入文件?我希望能够做到这样的事情:如何检查文件是否写入终端?
if is_writing_to_terminal:
sys.stdout.write('one thing')
else:
sys.stdout.write('another thing')
是否有某种方法来检查python进程的输出是否正在写入文件?我希望能够做到这样的事情:如何检查文件是否写入终端?
if is_writing_to_terminal:
sys.stdout.write('one thing')
else:
sys.stdout.write('another thing')
使用os.isatty
。这需要一个文件描述符(fd),可以通过fileno
成员获得。
>>> from os import isatty
>>> isatty(sys.stdout.fileno())
True
如果你想支持任意文件喜欢(如StringIO
),那么你必须检查类文件是否具有相关联的FD,因为不是所有的文件,喜欢做的事:
hasattr(f, "fileno") and isatty(f.fileno())
您可以使用os.isatty()
检查文件描述符是否是终端:
if os.isatty(sys.stdout.fileno()):
sys.stdout.write('one thing')
else:
sys.stdout.write('another thing')
嗯,所以有os.isatty之间'什么区别(sys.stdout.fileno())'和['sys.stdout.isatty ()'](http://docs.python.org/2 /library/stdtypes.html#file.isatty)? – Shep