python - Nohup 和 Python -u : it still doesn't log data in realtime

标签 python stdout nohup

在后台启动 Python 进程时,使用

nohup python myscript.py > test.log 2>&1 < /dev/null &

问题是 stdout已缓冲:数据实时写入test.log . this problem的常见解决方法是flush periodicallysys.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/

相关文章:

linux - 交换标准输入和标准错误后 grep 将无法工作

c - 如何使用 apr 从在新进程中运行的程序捕获 stdout/stderr 输出?

python - 如果我在 subprocess.Popen() 中不使用 stdout=subprocess.PIPE 有什么区别?

linux - 为什么这个脚本不能与 nohup 一起使用但没有?

python - 将 Array_list 值插入另一个空 Array_list

bash - 如何在将标准输出保持在屏幕上的同时通过管道传输它? (而不是输出文件)

带有 utf-8 和 nohup 的 python 打印语句

python - BeautifulSoup 的多个标签

python - Django 查询单下划线表现得像双下划线?

python - python 中的 matlabish "strncmp"