如何在Python中启动后台进程? [英] How to start a background process in Python?
问题描述
我正在尝试将Shell脚本移植到可读性更高的python版本。原始的shell脚本在后台使用&启动多个进程(实用程序,监视器等)。如何在python中达到相同的效果?我希望这些过程在Python脚本完成后不会消失。我确定它某种程度上与守护程序的概念有关,但是我找不到如何轻松实现此目的。
I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.
推荐答案
注意:此答案的发布时间比2009年发布时要少。现在建议使用其他答案中显示的子流程
模块在文档中
Note: This answer is less current than it was when posted in 2009. Using the subprocess
module shown in other answers is now recommended 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脚本相同的方式调用它,或者您可以生成
它:
If you want your process to start in the background you can either use system()
and call it in the same way your shell script did, or you can spawn
it:
import os
os.spawnl(os.P_DETACH, 'some_long_running_command')
(或者,您也可以尝试使用不太便携的 os.P_NOWAIT
标志)。
(or, alternatively, you may try the less portable os.P_NOWAIT
flag).
请参见此处的文档。
这篇关于如何在Python中启动后台进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!