在后台启动 Python 进程时,使用
nohup python myscript.py > test.log 2>&1 < /dev/null &
问题是 stdout
已缓冲:数据未实时写入test.log
. this problem的常见解决方法是flush periodically与 sys.stdout.flush()
,甚至更好,如建议的那样by this answer , 使用 python -u
:
nohup python -u myscript.py > test.log 2>&1 < /dev/null &
但这还不够。我注意到它在几个小时内工作,然后停止工作,即几个小时后test.log
不再实时写入,即使我使用了 nohup python -u ...
.
1) 这是重现问题的方法(我有一个标准的 Debian Jessie)。启动这个文件:
import time
import datetime
while True:
print datetime.datetime.now()
time.sleep(60)
与 nohup python -u myscript.py > test.log 2>&1 < /dev/null &
.
日志文件将在几个小时内更新,然后在 3 或 4 小时后,没有了。
2) 如何解决这个问题,无需插入stdout.flush()
代码中每 2 行(丑陋的解决方案)?
最佳答案
如果 python -u 似乎不适合您,下一个建议是用不缓冲输出的自定义类替换 sys.stdout。
Magnus Lycka provided this solution in a mailing list
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
import sys
sys.stdout = Unbuffered(sys.stdout)
print 'Unbuffered Output'
我看不出为什么 python -u 从您的示例中不起作用,但这应该可以为您解决问题。
关于python - Nohup 和 Python -u : it still doesn't log data in realtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34753765/