Skip to content Skip to sidebar Skip to footer

Capture Stdout Stderr Of Python Subprocess, When It Runs From Cron Or Rc.local

I have problem accessing output (stderr stdout) of a command when I do lunch it via cron or rc.local It works perfectly form regular shell, but fails via rc.local cat /root/watchdo

Solution 1:

There are multiple issues in your code:

  • pass the command and its args as a string when shell=True otherwise the args are passed to the shell itself instead of the command
  • you should use stderr=subprocess.STDOUT instead of 2>&1 if you meant to apply the latter to the whole pipeline and not just the last command in it
  • use p.communicate() instead of p.stdout.read(), p.stderr.read() otherwise the subprocess may stall if any of OS pipe buffers fill up
  • if you want to redirect the output to a file then you do not need to save it as a string first
import shlex
from subprocess import Popen, PIPE, STDOUT

withopen("/root/logfile", 'ab', 0) as logfile:
    p = Popen(shlex.split('gnokii ... +123456789xx'), 
              stdin=PIPE, stdout=logfile, stderr=STDOUT)
    p.communicate(b'TEST')

Redirect subprocess stderr to stdout doesn't apply because you redirect stdout explicitly.

Post a Comment for "Capture Stdout Stderr Of Python Subprocess, When It Runs From Cron Or Rc.local"