有没有办法找出标准输出在 Python 中重定向到的文件的名称 [英] Is there a way to find out the name of the file stdout is redirected to in Python
本文介绍了有没有办法找出标准输出在 Python 中重定向到的文件的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道如何使用 sys.stdout.isatty()
检测我的 Python 脚本的 stdout
是否被重定向 (>
) 但是有没有办法发现它被重定向到什么地方?
I know how to detect if my Python script's stdout
is being redirected (>
) using sys.stdout.isatty()
but is there a way to discover what it's being redirected to?
例如:
python my.py > somefile.txt
有没有办法在 Windows 和 Linux 上找到名称 somefile.txt
?
Is there a way to discover the name somefile.txt
on both Windows and Linux?
推荐答案
我怀疑您能否以独立于系统的方式做到这一点.在 Linux 上,以下工作有效:
I doubt you can do that in a system-independent way. On Linux, the following works:
import os
my_output_file = os.readlink('/proc/%d/fd/1' % os.getpid())
这篇关于有没有办法找出标准输出在 Python 中重定向到的文件的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文