fwi*_*llo 4 python stdout buffering stderr unbuffered
我正在纠结 python 的问题。我在 Red Hat Enterprise Linux Server 版本 7.1 (Maipo) 上使用了 Python 2.7.13 和 Python 3.6.0。为了监视进程输出,我想tail -f实时查看 STDOUT 和 STDERR。这里的关键字是无缓冲输出。互联网上的许多建议都说使用python -u ...或 环境变量 PYTHONUNBUFFERED 像PYTHONUNBUFFERED=1 python ...或stdbuf -e0 -o0 python ...。然而,以下测试脚本没有任何作用。
import sys
import time
while(True):
print("Test String")
time.sleep(1);
Run Code Online (Sandbox Code Playgroud)
对于所有不同的命令,我总是有缓冲的输出。即使当我想使用 STDERR 时。它仍然是缓冲的,这真的让我很困惑,因为默认情况下 STDERR 应该是不缓冲的。使用sys.stdout.flush()orsys.stderr.flush()也没有完成这项工作。flush=True当在内部使用时,print()它会按预期工作。
我正在寻找一种不需要编辑代码的解决方案,因为我无法编辑所有程序以获得无缓冲并立即刷新输出。我怎样才能实现这个目标?
期待您的答复!
最好的祝愿!
您可以覆盖print()Python 3 中的函数。这样您就不需要更改print()脚本中的每个函数。
import builtins
def print(*args):
builtins.print(*args, sep=' ', end='\n', file=None, flush=True)
print(
'hello', 'world',
'I have overrode print() function!',
1, # integer
[1, 2], # list
{1, 2}, # set
(1, 2), # tuple
{1: 2} # dict
)
Run Code Online (Sandbox Code Playgroud)
将打印:
hello world I have overrode print() function! 1 [1, 2] {1, 2} (1, 2) {1: 2}
Run Code Online (Sandbox Code Playgroud)