How to spawn detached background process on Linux in either bash or python(如何在 bash 或 python 中在 Linux 上生成分离的后台进程)
问题描述
我在 Linux 上有一个长时间运行的 python 脚本,在某些情况下它需要执行命令来停止和重新启动自身.所以,我想要一个外部脚本(在 bash 或 python 中)执行命令以重新启动原始脚本.让我详细说明.
I have a long running python script on Linux, and in some situations it needs to execute a command to stop and restart itself. So, I would like to have an external script (either in bash or python) that executes command to restart the original script. Let me elaborate.
假设我有 original_script.py.在 original_script.py 我有这个无限循环:
Suppose I have original_script.py. In original_script.py I have this in an infinite loop:
if some_error_condition:
somehow call external script external.sh or external.py
假设我可以调用 external.sh 并且它包含以下内容:
Let's suppose I can call external.sh and it contains this:
#!/bin/bash
command_to_restart_original_script
最后,我知道了命令command_to_restart_original_script".那不是问题.需要的是以某种方式调用外部脚本external.sh"的python命令.我需要外部脚本(这是一个子进程)在父进程 original_script.py 重新启动时继续运行,即我需要子进程被分离/守护.我该怎么做?
Finally, I know the command "command_to_restart_original_script". That isn't the problem. What need is the python command to "somehow call external script external.sh". I need the external script (which is a child process) to keep running as the parent process original_script.py is restarting, ie I need the child process to be detached/daemonized. How do I do this?
推荐答案
我在各个地方找到了很多建议,但唯一对我有用的答案是:如何在后台启动和运行外部脚本?
I found lots of suggestions in various places, but the only answer that worked for me was this: How to launch and run external script in background?
import subprocess
subprocess.Popen(["nohup", "python", "test.py"])
在我的例子中,我运行了一个名为 longrun.sh 的脚本,所以实际的命令是:
In my case I ran a script called longrun.sh so the actual command is:
import subprocess
subprocess.Popen(["nohup", "/bin/bash", "longrun.sh"])
我使用这个 run.py 对此进行了测试:
I tested this using this run.py:
import subprocess
subprocess.Popen(["nohup", "/bin/bash", "longrun.sh"])
print "Done!"
我验证了(使用 ps -ax | grep longrun)longrun.sh 确实在 run.py 退出后很长时间在后台运行.
and I verified (using ps -ax | grep longrun) that longrun.sh does indeed run in the background long after run.py exits.
这篇关于如何在 bash 或 python 中在 Linux 上生成分离的后台进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 bash 或 python 中在 Linux 上生成分离的后台进程


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