有没有一种方法在Python中调用外部程序而不等待其执行完成?
我尝试了这个方法,但没有成功:
os.system("external_program &")
通常,如果我在bash shell中调用
external_program &
,它会作为后台进程执行。
我如何在python中做到这一点?对于我的特殊情况,创建另一个线程行不通。在主python脚本完成后,外部程序应该继续执行。有没有一种方法在Python中调用外部程序而不等待其执行完成?
我尝试了这个方法,但没有成功:
os.system("external_program &")
external_program &
,它会作为后台进程执行。
我如何在python中做到这一点?对于我的特殊情况,创建另一个线程行不通。在主python脚本完成后,外部程序应该继续执行。是的,可以使用subprocess
模块。例如:
p = subprocess.Popen(['external_program', 'arg1', 'arg2'])
# Process is now running in the background, do other stuff...
...
# Check if process has completed
if p.poll() is not None:
...
...
# Wait for process to complete
p.wait()
wait()
函数,这很简单。如果在子进程仍在运行时退出,则其将在后台继续运行。 - Adam Rosenfieldp = subprocess.Popen(['thing'])
代替os.system("thing &")
(不需要使用&
,也不需要使用shell),然后进行任何其他你想要做的操作。因为你创建了一个子进程,所以p
将存在并在后台运行,就像shell使用&
一样,你可以使用p.wait()
最终清除它。如果thing
由于写入管道或其他原因而阻塞,情况会变得更加复杂和微妙,但是还有其他问题会详细解释这一点。 - tripleee