Skip to main content
 首页 » 编程设计

python之什么时候应该使用 Popen() 什么时候应该使用 call()

2025年05月04日14sky-heaven

警告:Python 新手。

想听听实际使用它的专业人士的意见:

subprocess.Popen() 和 subprocess.call() 之间的主要区别是什么?什么时候使用它们最好?

除非您想了解为什么我在思考这个问题或者您的回答应该围绕什么展开,否则您现在可以停止阅读。

我之所以提出这个问题,是因为我正在解决脚本中的一个问题,我开始使用 subprocess.Popen(),最终调用了系统暂停,然后想删除 .创建系统暂停的 exe,但我注意到 Popen(),所有命令似乎都一起运行(.exe 上的删除在 exe 关闭之前执行..),尽管我试过了添加 communicate()。

这是我上面描述的假代码:

subprocess.Popen(r'type pause.exe > c:\worker.exe', shell=True).communicate() 
subprocess.Popen(r'c:\worker.exe', shell=True).communicate() 
subprocess.Popen(r'del c:\worker.exe', shell=True).communicate() 

请您参考如下方法:

subprocess.call(*popenargs, **kwargs) Run command with arguments. Wait for command to complete, then return the returncode attribute.

如果您创建一个Popen对象,您必须自己调用sp.wait()。

如果您使用调用,那已经为您完成了。