我正在尝试使用subprocess.call在Python中运行外部应用程序。根据我的阅读,subprocess.call不应该被阻塞,除非你调用Popen.wait,但是对于我来说,它一直阻塞直到外部应用程序退出。我该如何解决这个问题?
我正在尝试使用subprocess.call在Python中运行外部应用程序。根据我的阅读,subprocess.call不应该被阻塞,除非你调用Popen.wait,但是对于我来说,它一直阻塞直到外部应用程序退出。我该如何解决这个问题?
您阅读文档的方法不正确。根据文档:
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
subprocess
中的代码实际上非常简单易读。只需查看 3.3 或 2.7 版本(视情况而定),您就可以知道它在做什么。
例如,call
的代码如下:
def call(*popenargs, timeout=None, **kwargs):
"""Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
"""
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout)
except:
p.kill()
p.wait()
raise
您可以不调用wait
函数来实现同样的功能。创建一个Popen
对象,不要在其上调用wait
函数,这正是您想要的。