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

如何在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.

推荐答案

尝试在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中产生一个新的独立进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 13:19