如何在 Python 中生成一个新的独立进程
问题描述
我有一些 Python 代码偶尔需要跨越一个新进程以即发即弃"的方式运行 shell 脚本,即没有阻塞.shell 脚本不会与原始 Python 代码通信,实际上可能会终止调用 Python 进程,因此启动的 shell 脚本不能是调用 Python 进程的子进程.我需要它作为一个独立的进程启动.
I have a some Python code that occasionally needs to span a new process to run a shell script in a "fire and forget" manner, i.e. without blocking. The shell script will not communicate with the original Python code and will in fact probably terminate the calling Python process, so the launched shell script cannot be a child process of the calling Python process. I need it to be launched as an independent process.
换句话说,假设我有 mycode.py 并启动 script.sh.然后 mycode.py 将继续处理而不会阻塞.脚本 script.sh 将独立做一些事情,然后实际停止并重新启动 mycode.py.所以运行script.py的进程必须完全独立于mycode.py.我该怎么做?我认为 subprocess.Popen 不会阻塞,但仍会创建一个子进程,一旦 mycode.py 停止就会终止,这不是我想要的.
In other words, let's say I have mycode.py and that launches script.sh. Then mycode.py will continue processing without blocking. The script script.sh will do some things independently and will then actually stop and restart mycode.py. So the process that runs script.py must be completely independent of mycode.py. How exactly can I do this? I think subprocess.Popen will not block, but will still create a child process that terminates as soon as mycode.py stops, which is not what I want.
解决方案
尝试在前面加上 "nohup" 到 script.sh.您可能需要决定如何处理 stdout 和 stderr;我只是把它放在示例中.
Try prepending "nohup" to script.sh. You'll probably need to decide what to do with stdout and stderr; I just drop it in the example.
import os
from subprocess import Popen
devnull = open(os.devnull, 'wb') # Use this in Python < 3.3
# Python >= 3.3 has subprocess.DEVNULL
Popen(['nohup', 'script.sh'], stdout=devnull, stderr=devnull)
相关文章