启动进程并阻塞直到完成的最佳方法
我听说subprocess.Popen这个东西不会阻塞,也就是说它会在后台运行,等于你的Python程序不会等它完成就继续执行。不过,我并不想要这样的效果。
我的程序需要调用一个外部的Python程序,而我对这个程序没有控制权。它不会返回任何状态码,只是运行、处理文件,然后结束。我希望在调用这个程序后,只有等它完成了,我的Python程序才继续执行。请问我该怎么做呢?
3 个回答
1
最好的方法是使用 communicate
这个方法:http://docs.python.org/library/subprocess.html#subprocess.Popen.communicate
另外,你也可以看看 wait
这个方法,它解释了为什么大多数情况下你应该使用 communicate
而不是 wait
:http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
2
使用 call
方法来自 subprocess 模块。
subprocess.call(*popenargs, **kwargs) 运行命令和参数。等待命令完成后,返回返回码。
查看详细信息 → http://docs.python.org/library/subprocess.html#subprocess.call
5
在子进程上调用 communicate 或 wait 方法。