如何在 Python 中生成一个新的独立进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20646519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:55:54  来源:igfitidea点击:

How to spawn a new independent process in Python

pythonsubprocessforkdaemonspawn

提问by Marc

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.

我有一些 Python 代码,偶尔需要跨越一个新进程以“即发即忘”的方式运行 shell 脚本,即没有阻塞。shell 脚本不会与原始 Python 代码通信,实际上可能会终止调用 Python 进程,因此启动的 shell 脚本不能是调用 Python 进程的子进程。我需要它作为一个独立的进程启动。

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.

换句话说,假设我有 mycode.py 并启动了 script.sh。然后 mycode.py 将继续处理而不阻塞。脚本 script.sh 会独立做一些事情,然后实际上会停止并重新启动 mycode.py。所以运行script.py的进程必须完全独立于mycode.py。我怎么能做到这一点?我认为 subprocess.Popen 不会阻塞,但仍会创建一个子进程,该进程在 mycode.py 停止后立即终止,这不是我想要的。

采纳答案by Lasse

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.

尝试在 script.sh之前添加“ nohup”。您可能需要决定如何处理 stdout 和 stderr;我只是把它放在例子中。

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)

回答by Steve Barnes

Just use subprocess.Popen. The following works OK for me on Windows XP / Windows 7 and Python 2.5.4, 2.6.6, and 2.7.4. And after being converted with py2exe - not tried 3.3 - it comes from the need to delete expired test software on the clients machine.

只需使用 subprocess.Popen。以下在 Windows XP / Windows 7 和 Python 2.5.4、2.6.6 和 2.7.4 上对我来说工作正常。用py2exe转换后——3.3没试过——是因为需要删除客户端机器上过期的测试软件

import os
import subprocess
import sys
from tempfile import gettempdir

def ExitAndDestroy(ProgPath):
    """ Exit and destroy """
    absp = os.path.abspath(ProgPath)
    fn = os.path.join(gettempdir(), 'SelfDestruct.bat')
    script_lines = [
        '@rem Self Destruct Script',
        '@echo ERROR - Attempting to run expired test only software',
        '@pause',
        '@del /F /Q %s' % (absp),
        '@echo Deleted Offending File!',
        '@del /F /Q %s\n' % (fn),
        #'@exit\n',
        ]
    bf = open(fn, 'wt')
    bf.write('\n'.join(script_lines))
    bf.flush()
    bf.close()
    p = subprocess.Popen([fn], shell=False)
    sys.exit(-1)

if __name__ == "__main__":
   ExitAndDestroy(sys.argv[0])