Python 如何检查文件是否写入终端?
是否有某种方法可以检查python进程的输出是否正在写入文件?我希望能够做到以下几点:Python 如何检查文件是否写入终端?,python,unix,Python,Unix,是否有某种方法可以检查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(s
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())
和?