from subproccess import *
x = Popen('sh /root/script.sh', stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=True)
print x.stdout.readline()
print x.stderr.readline()
由于您没有发布任何相关代码,因此它的外观如下。请注意,即使没有可获取的内容,readline 仍会为您提供输出,因为 stderr 有时会“挂起”等待输出,但如果您使用的是子进程,这是要走的路。
from subprocess import PIPE, Popen
x = Popen(['ls', '-l'], stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=False)
while 1:
if x.poll() != None:
break
_queue.put(x.stdout.readline())
sleep(0.2)
像这样的东西应该工作。如果您不需要分离两个输出,而只想读取数据并将其添加到队列中,则可以执行以下操作:
x = Popen(['ls', '-l'], stdout=PIPE, stderr=STDOUT, stdin=PIPE, shell=False)
这是我通常做的
(我并不是说这是最好的做法,但它确实有效)
from threading import Thread, enumerate
from subprocess import Popen, PIPE
from time import sleep
class nonBlockingStderr(Thread):
def __init__(self, handle):
self.handle = handle
self.stderrOutput = []
Thread.__init__(self)
self.start()
def stderr(self):
if len(self.stderrOutput) <= 0:
return ''
else:
ret = self.stderrOutput[0]
self.stderrOutput = self.stderrOutput[1:]
return ret
def run(self):
while 1:
line = self.handle.readline()
if len(line) > 0:
self.stderrOutput.append(line)
sleep(0.1)
from subprocess import PIPE, Popen
x = Popen(['ls', '-l'], stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=False)
errHandle = nonBlockingStderr(x.stderr)
while 1:
if x.poll() != None:
break
_queue.put(errHandle.stderr())
_queue.put(x.stdout.readline())
sleep(0.2)