3

I am running a python script on startup like this (in /etc/rc.local):

/usr/bin/python3 -u /path/to/script.py > /path/to/output.log 2> /path/to/output.log &

(The -u option was a failed attempt to fix this problem.) However, my stdout output (such as print('abc')) does not end up in the log file. After noticing that python errors (such as uncaught exceptions) do end up in the log, I changed all my prints to go to stderr as such:

def eprint(msg):
    sys.stderr.write(msg)

eprint('Hello')
devicepath = '/dev/hidraw0'
path = Path(devicepath)

while not path.is_char_device():
    eprint('No device found')
    time.sleep(1)

But not even those messages make it to output.log. So now my program is running perfectly, but I have no logs at all. Any ideas how to make sure that my output ends up where it's supposed to go?

  • Although I don't think it's the cause of the problem, try 2>&1 instead of the last redirection. – goldilocks Sep 26 '16 at 13:23
2

As your command line is written, you're trying to open /path/to/output.log twice, to redirect two streams in it. Since redirections are processed right to left, 2> /path/to/output.log gets executed first. As a result, the second redirection, > /path/to/output.log is stuck with a file which is already open, and silently fails.

Either redirect one stream into the other first (with 2>&1 as goldilocks suggested) or log normal output and errors into two separate log files.

I'm not sure why your sys.stderr.write lines didn't produce any output. My best guess is that they don't have newlines so they got lost in stream buffers somehow. Try adding newline characters at the end, or use

def eprint(msg):
    print >> sys.stderr, msg
  • I used to redirect the output to two files, that didn't (and doesn't) help, unfortunately. I can't use the >> operator since I'm using Python 3. – TheWolf Sep 27 '16 at 7:04
  • 1
    Apparently, the missing newline was actually the problem :-O Changing the eprint function to sys.stderr.write(msg + "\n") solved it. Thanks! – TheWolf Sep 27 '16 at 7:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.