问题描述
我在 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 上生成分离的后台进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!