如何在 Linux 上使用 bash 或 python 生成分离的后台进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29661527/
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
How to spawn detached background process on Linux in either bash or python
提问by Marc
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.
我在 Linux 上有一个长时间运行的 python 脚本,在某些情况下它需要执行一个命令来停止和重新启动自己。所以,我想要一个外部脚本(在 bash 或 python 中)来执行命令以重新启动原始脚本。让我详细说明一下。
Suppose I have original_script.py. In original_script.py I have this in an infinite loop:
假设我有 original_script.py。在 original_script.py 我有一个无限循环:
if some_error_condition:
somehow call external script external.sh or external.py
Let's suppose I can call external.sh and it contains this:
假设我可以调用 external.sh 并且它包含以下内容:
#!/bin/bash
command_to_restart_original_script
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?
最后,我知道命令“command_to_restart_original_script”。那不是问题。需要的是python命令“以某种方式调用外部脚本external.sh”。我需要外部脚本(它是一个子进程)在父进程 original_script.py 重新启动时继续运行,即我需要分离/守护子进程。我该怎么做呢?
回答by Marc
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"])
In my case I ran a script called longrun.sh so the actual command is:
就我而言,我运行了一个名为 longrun.sh 的脚本,因此实际命令是:
import subprocess
subprocess.Popen(["nohup", "/bin/bash", "longrun.sh"])
I tested this using this run.py:
我使用这个 run.py 对此进行了测试:
import subprocess
subprocess.Popen(["nohup", "/bin/bash", "longrun.sh"])
print "Done!"
and I verified (using ps -ax | grep longrun) that longrun.sh does indeed run in the background long after run.py exits.
并且我验证(使用 ps -ax | grep longrun)longrun.sh 确实在 run.py 退出后很久确实在后台运行。