Python 2.7 理解python子进程popen异步
我的理解是subprocess.popen是一个异步调用,在调用后附加.wait()将使其同步。第一次调用完成后,是否会执行第二次popen调用Python 2.7 理解python子进程popen异步,python-2.7,Python 2.7,我的理解是subprocess.popen是一个异步调用,在调用后附加.wait()将使其同步。第一次调用完成后,是否会执行第二次popen调用 proc1 = subprocess.Popen(first_command, stdout=subprocess.PIPE, shell=True) proc2 = subprocess.Popen(second_command, stdin=proc1.stdout, stdout=self.fw, shell=True) 我试图确定何时需要使用
proc1 = subprocess.Popen(first_command, stdout=subprocess.PIPE, shell=True)
proc2 = subprocess.Popen(second_command, stdin=proc1.stdout, stdout=self.fw, shell=True)
我试图确定何时需要使用wait(),以及为什么在上面的示例popen语句中使用wait()会导致错误,例如:
proc1 = subprocess.Popen(first_command, stdout=subprocess.PIPE, shell=True).wait() # throws exception
proc2 = subprocess.Popen(second_command, stdin=proc1.stdout, stdout=self.fw, shell=True).wait() # seems ok
经过大量的尝试和错误,并重新阅读其他帖子和文档,这就是有效的方法
proc1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE, shell=True)
# don't put wait here because of potential deadlock if stdout buffer gets full and we're waiting for proc2 to consume buffer then we're deadlocked
proc2 = subprocess.Popen(cmd2, stdin=proc1.stdout, stdout=self.fw, shell=True)
# ok to wait here
proc2.wait()
# ok to test return code after proc2 completes
if proc2.returncode != 0:
print('Error spawning cmd2')
else:
print('Success spawning cmd2')
希望这能帮助其他人