如何在Python中启动后台进程?

2024-04-25 05:24:48 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

jkp的解决方案工作时,较新的工作方式(以及文档推荐的方式)是使用subprocess模块。对于简单的命令,它是等价的,但是如果你想做一些复杂的事情,它提供了更多的选项。

您的案例示例:

import subprocess
subprocess.Popen(["rm","-r","some.file"])

这将在后台运行rm -r somefile。请注意,对从Popen返回的对象调用.communicate()将被阻塞,直到它完成为止,因此,如果希望它在后台运行,请不要这样做:

import subprocess
ls_output=subprocess.Popen(["sleep", "30"])
ls_output.communicate()  # Will block for 30 seconds

请参阅文档here

另外,还有一点需要澄清:这里使用的“Background”纯粹是一个shell概念;从技术上讲,您的意思是希望在等待进程完成时生成一个没有阻塞的进程。不过,我在这里使用“background”来指代shell的类似背景的行为。

注意:此答案比2009年发布时的更新率低。现在建议使用其他答案中显示的subprocess模块in the docs

(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)


如果希望进程在后台启动,可以使用system(),并使用与shell脚本相同的方式调用它,也可以spawn

import os
os.spawnl(os.P_DETACH, 'some_long_running_command')

(或者,您也可以尝试使用不太便携的os.P_NOWAIT标志)。

请参阅documentation here

你可能想要"How to call an external command in Python"的答案。

最简单的方法是使用os.system函数,例如:

import os
os.system("some_command &")

基本上,传递给system函数的任何内容都将执行,就像在脚本中将其传递给shell一样。

相关问题 更多 >