基于这个Stackoverflow问题,我尝试通过Python获取进程的输出。
下面是代码:
from subprocess import Popen, PIPE
connection_string = "yowsup-cli demos --yowsup --config config"
popen_parameters = connection_string.split(" ")
proc = Popen(popen_parameters, stdout=PIPE, stderr=PIPE)
while True:
line = proc.stdout.readline()
if line != '':
#the real code does filtering here
print "Result:", line.rstrip()
proc.stdout.flush()不幸的是,没有返回任何内容。顺便说一句,我需要与发送和接收数据的进程进行交互。我怎么才能做到这一点呢?
谢谢!
发布于 2015-03-22 00:00:42
即使在发送了命令的输出之后,也不会有条件地退出while循环。试试这个:
if line != '':
#the real code does filtering here
print "Result:", line.rstrip()
else:
break
发布于 2015-03-22 15:05:25
首先,如果子进程实际上正在向其stdout写入数据,那么您的代码应该可以正常工作。如果命令中有错误,输出可能会显示在stderr上。
但请注意,您的代码不会退出循环,因此您需要修复它,例如,当您读取空字符串时调用break。
但还有一种更好的方法。使用Popen.communicate()而不是直接读取子进程的stdout
from subprocess import Popen, PIPE
connection_string = "yowsup-cli demos --yowsup --config config"
popen_parameters = connection_string.split(" ")
proc = Popen(popen_parameters, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
if out:
print "Received stdout output of length {} from child process".format(len(out))
print out
elif err:
print "Received stderr output of length {} from child process".format(len(err))
print err您的问题的另一部分涉及与子进程的交互。在启动该子进程并向其发送一个输入的简单情况下,仍然可以通过向其传递一个字符串参数来使用Popen.communicate()。注意,您还需要设置stdin管道。所以,如上所述,但是:
proc = Popen(popen_parameters, stdin=PIPE, stdout=PIPE, stderr=PIPE)
data = 'data to send to child'
out, err = proc.communicate(data)如果您与孩子的交互比较复杂,则应该考虑使用专为此用途而设计的pexpect模块。虽然使用Popen()可以做到这一点,但在读/写管道的过程中存在一些缓冲和死锁问题,因此最好避免这种情况。
https://stackoverflow.com/questions/29183396
复制相似问题