如何在 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 年发布时相比,此答案的更新程度较低.使用 subprocess
模块现在推荐在其他答案中显示在文档中一个>
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
(请注意,subprocess 模块为生成新进程和检索其结果提供了更强大的工具;使用该模块比使用这些函数更可取.)
(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
它:
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屋!