我刚刚发现了'envoy'模块,它是由请求创建者创建的python子进程的包装器。
我对'connect'函数有一个问题:每次我使用它时,都会导致僵尸进程,我无法获得status_code或结果。
c=envoy.connect("ls -al")
c.status_code == None
True
如果我做'ps -ef | grep thepid',我会得到一个'已经不存在'的pid。
我可以通过执行os.wait()或c._process.wait()来杀死僵尸,但是我无法获得命令的结果(stdout)...
任何的想法?
在您的情况下,您应该使用run()
方法
特使文件建议:
r = envoy.run(cmd)
print r.status_code, r.std_out
但是如果您希望异步运行命令,可以使用connect()
,然后使用block()
调用block()
后,返回代码变为可用。但是block()会阻止你的程序,所以逻辑应该是。
c1=envoy.connect(cmd1)
c2=envoy.connect(cmd2)
c3=envoy.connect(cmd3)
... more staff ...
c1.block()
print c1.status_code
但是我无法得到命令的结果(stdout)......
ConnectedCommand
(由envoy.connect()
返回的类型)似乎没有准备好。特别是,如果命令接收/生成足够的(取决于平台)输入/输出,则该命令可能会死锁。
除了调用c.block()
,它也适用于活着的过程;你可以删除对该命令的所有引用,并使用del c
来获取僵尸。如果子过程没有死;在下一个子进程开始运行清理方法之前,它们不会被收集(这取决于实现)。
如果envoy.run()
功能不足以完成您的任务;你可以直接使用subprocess
模块。例如,将输入传递给多个进程并收集相应的结果;你可以使用ThreadPool
和.communicate()
方法:
#!/usr/bin/env python
from multiprocessing.pool import ThreadPool
from subprocess import Popen, PIPE
def process(child_input):
child, input = child_input # unpack arguments
return child.communicate(input)[0], child.returncode # get the result
# define input to be pass to subprocesses
params = b"a b c".split()
# start subprocesses (the command is just an example, use yours instead)
children = [Popen("( echo -n {0}; sleep {0}; cat )".format(len(params) - i),
shell=True, stdin=PIPE, stdout=PIPE)
for i in range(len(params))]
# use threads to wait for results in parallel
pool = ThreadPool(len(params))
for output, returncode in pool.imap_unordered(process, zip(children, params)):
if returncode == 0:
print("Got %r" % output)
无论原始顺序如何,父项的结果越早,父母就越少。
没有僵尸,如果输入/输出超过管道缓冲区,它不会死锁。