Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

stdout - Nohup and Python -u : it still doesn't log data in realtime

When launching a Python process, in background, with

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

the problem is that stdout is buffered: the data is not written in realtime to test.log. The common solution to this problem is to flush periodically with sys.stdout.flush(), or even better, as suggested by this answer, to use python -u :

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

But this is not enough. I noticed that it worked during a few hours, and then, it stopped working, i.e. after a few hours test.log is not written in realtime anymore, even if I used nohup python -u ....

1) This is how to reproduce the problem (I have a standard Debian Jessie). Start this file:

import time
import datetime
while True:
    print datetime.datetime.now()
    time.sleep(60)

with nohup python -u myscript.py > test.log 2>&1 < /dev/null &. The log file will be updated during a few hours, and then after 3 or 4 hours, nothing anymore.

2) How to solve this problem, without having to insert stdout.flush() every 2 lines in the code (ugly solution) ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If python -u does not seem to be working for you, the next suggestion would be to replace sys.stdout with a custom class that does not buffer output.

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'

I can't see why python -u wouldn't work from your example, but this should solve the issue for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...