如何产卵超然的后台进程在Linux上在任bash或蟒蛇 [英] How to spawn detached background process on Linux in either bash or python
问题描述
我对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。我需要的外部脚本(这是一个子进程),以确保运行的父进程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?
推荐答案
我发现很多在各个地方的建议,但只为我工作的答案是这样的:
<一href=\"http://stackoverflow.com/questions/1605520/how-to-launch-and-run-external-script-in-background\">How推出并在后台运行外部脚本?
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?
导入子
subprocess.Popen([的nohup,巨蟒,test.py])
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:
导入子
subprocess.Popen([的nohup,/斌/ bash的,longrun.sh])
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.sh确实run.py退出后长期在backgreoun运行
and I verified (using ps -ax | grep longrun) that longrun.sh does indeed run in the backgreoun long after run.py exits.
这篇关于如何产卵超然的后台进程在Linux上在任bash或蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!