python-daemon not logging stdout redirection

2019-06-28 05:18发布

问题:

I am using python-daemon in my code that has print statements in it. I want to send them to a file so I ran the following:

python server.py >> log.out

However, nothing goes in log.out.

Can anyone tell me what I need to do?

Thanks.

回答1:

The DaemonContext object allows redirecting stdout/stderr/stdin when you create the object. For example:

import os
import daemon


if __name__ == '__main__':
    here = os.path.dirname(os.path.abspath(__file__))
    out = open('checking_print.log', 'w+')

    with daemon.DaemonContext(working_directory=here, stdout=out):
        for i in range(1, 1000):
            print('Counting ... %s' % i)

You should be able to cat checking_print.log and see the output from the print statements.

A good reference for the DaemonContext object is PEP 3143.



回答2:

if you have an error in your code it will not be written to the file. See http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html

Try creating this file:

print 'stdout'
raise Exception('stderr')


回答3:

If it's already running as a daemon you'll most likely need to force redirection of STDOUT, STDERR etc. You can read more on I/O Redirection here.

python server.py 2>log.out >&2