How to spawn a new independent process in Python(如何在 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)
这篇关于如何在 Python 中生成一个新的独立进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 中生成一个新的独立进程


基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01