重定向 FD 后如何写入标准输出
How to write to stdout after redirecting FD
请查看下面的 python 代码。
so = open('/tmp/test.log', 'a+')
os.dup2(so.fileno(), sys.stdout.fileno())
执行那段代码后,我仍然希望能够在标准标准输出上打印一些东西。
我已经试过了:
print('Foo\n', file=sys.__stdout__)
根据 documentation 可能是一条路要走。
sys.__stdin__
sys.__stdout__
sys.__stderr__
These objects contain the original values of stdin, stderr and stdout
at the start of the program. They are used during finalization, and
could be useful to print to the actual standard stream no matter if
the sys.std* object has been redirected.
但事实并非如此。它仍在记录到我的 test.log 文件。
Python版本:3.4.8
如有任何帮助,我们将不胜感激。
sys.__stdout__
不起作用的原因是因为您用 os.dup2()
替换了原始标准输出的文件描述符,所以 any Python 文件对象基于它将打印到新打开的文件。当您执行 dup2
时,旧的标准输出实际上会 关闭 ,因此无法恢复它。
如果你想让所有使用sys.stdout
的Python代码打印到/tmp/test.log
,打开一个新文件并将其分配给sys.stdout
.
sys.stdout = open('/tmp/test.log', 'a+')
原来的 sys.stdout
将作为 sys.__stdout__
保持可用。
如果您还想重定向任何直接写入 sys.stdout.fileno() 的代码,包括您以 os.system()
或 subprocess.call()
开始的子进程,同时保持对原始标准输出的访问,事情变得更加复杂:您需要先 dup()
stdout 并保存它,然后使用 dup2()
调用来替换 FD 1:
saved_stdout_fd = os.dup(sys.stdout.fileno())
saved_stdout = os.fdopen(saved_stdout_fd,'w')
so = open('/tmp/test.log', 'a+')
os.dup2(so.fileno(), sys.stdout.fileno())
现在 sys.stdout
转到您的 /tmp/test.log
并且 saved_stdout
将写入原始标准输出。
请查看下面的 python 代码。
so = open('/tmp/test.log', 'a+')
os.dup2(so.fileno(), sys.stdout.fileno())
执行那段代码后,我仍然希望能够在标准标准输出上打印一些东西。
我已经试过了:
print('Foo\n', file=sys.__stdout__)
根据 documentation 可能是一条路要走。
sys.__stdin__
sys.__stdout__
sys.__stderr__
These objects contain the original values of stdin, stderr and stdout at the start of the program. They are used during finalization, and could be useful to print to the actual standard stream no matter if the sys.std* object has been redirected.
但事实并非如此。它仍在记录到我的 test.log 文件。
Python版本:3.4.8
如有任何帮助,我们将不胜感激。
sys.__stdout__
不起作用的原因是因为您用 os.dup2()
替换了原始标准输出的文件描述符,所以 any Python 文件对象基于它将打印到新打开的文件。当您执行 dup2
时,旧的标准输出实际上会 关闭 ,因此无法恢复它。
如果你想让所有使用sys.stdout
的Python代码打印到/tmp/test.log
,打开一个新文件并将其分配给sys.stdout
.
sys.stdout = open('/tmp/test.log', 'a+')
原来的 sys.stdout
将作为 sys.__stdout__
保持可用。
如果您还想重定向任何直接写入 sys.stdout.fileno() 的代码,包括您以 os.system()
或 subprocess.call()
开始的子进程,同时保持对原始标准输出的访问,事情变得更加复杂:您需要先 dup()
stdout 并保存它,然后使用 dup2()
调用来替换 FD 1:
saved_stdout_fd = os.dup(sys.stdout.fileno())
saved_stdout = os.fdopen(saved_stdout_fd,'w')
so = open('/tmp/test.log', 'a+')
os.dup2(so.fileno(), sys.stdout.fileno())
现在 sys.stdout
转到您的 /tmp/test.log
并且 saved_stdout
将写入原始标准输出。