Skip to main content
 首页 » 编程设计

python之捕获 python 子进程的 stdout stderr,当它从 cron 或 rc.local 运行时

2025年05月04日14jackei

当我通过cron 或 rc.local

执行命令时,访问命令的输出 (stderr stdout) 时遇到问题

它在常规 shell 中完美运行,但通过 rc.local 失败

cat /root/watchdog.py  
import subprocess 
    cmd = ( 'echo "TEST" |gnokii --config /root/.config/gnokii/config --sendsms +123456789xx ') 
    #p = subprocess.Popen([cmd, '2>&1'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) 
    p = subprocess.Popen([cmd, '2>&1'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) 
    output = p.stdout.read() 
    output += p.stderr.read() 
    logFile = open("/root/logfile", 'a+') 
    #####  
    #Idea to read line by line: 
    #output = '' 
    #    for line in iter(p.stdout.readline,''): 
    #       print "captured line: %s" % line.rstrip() 
    #       #logFile.write(line.rstrip()) 
    #       output += line 
    logFile.write(output) 
    logFile.close() 

从控制台运行时的输出如下:

/root/watchdog.py  
GNOKII Version 0.6.30 
Cannot open logfile /root/.cache/gnokii/gnokii-errors 
WARNING: cannot open logfile, logs will be directed to stderr 
Send succeeded with reference 186! 

在我的 rc.local 中

/root/watchdog.py  > /root/mywatchPY.out 2>&1 &  

这看起来很有趣: Redirect subprocess stderr to stdout 但这并没有解决问题。

知道如何在没有完整 shell 的情况下捕获子进程运行的 sdterr/stdout 吗?

请您参考如下方法:

您的代码中存在多个问题:

  • 当 shell=True 时将命令及其参数作为字符串传递,否则参数将传递给 shell 本身而不是命令
  • 你应该使用 stderr=subprocess.STDOUT 而不是 2>&1 如果你想将 2>&1 应用于整个管道而不仅仅是其中的最后一个命令
  • 使用p.communicate()代替p.stdout.read(),p.stderr.read()否则子进程如果任何操作系统管道缓冲区已满,可能会停止
  • 如果你想将输出重定向到一个文件,那么你不需要先将它保存为一个字符串
import shlex 
from subprocess import Popen, PIPE, STDOUT 
 
with open("/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 不适用,因为您明确重定向了 stdout。