在通过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,但是它不能解决问题。
知道如何捕获子进程的sdterr/stdout而没有完整的shell吗?
发布于 2014-08-25 20:26:09
代码中存在多个问题:
shell=True时,将命令及其args作为字符串传递,否则args将传递给shell本身而不是命令。stderr=subprocess.STDOUT应用于整个管道,而不仅仅是其中的最后一个命令,那么您应该使用2>&1而不是2>&1。p.communicate()而不是p.stdout.read(),否则如果OS管道缓冲区被填满,子进程可能会停止。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。
https://stackoverflow.com/questions/25415143
复制相似问题