Python 在后台执行子进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32577071/
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
Execute Subprocess in Background
提问by dbishop
I have a python script which takes an input, formats it into a command which calls another script on the server, and then executes using subprocess:
我有一个 python 脚本,它接受输入,将其格式化为一个命令,该命令调用服务器上的另一个脚本,然后使用子进程执行:
import sys, subprocess
thingy = sys.argv[1]
command = 'usr/local/bin/otherscript.pl {0} &'.format(thingy)
command_list = command.split()
subprocess.call(command_list)
I append &
to the end because otherscript.pl
takes some time to execute, and I prefer to have run in the background. However, the script still seems to execute without giving me back control to the shell, and I have to wait until execution finishes to get back to my prompt. Is there another way to use subprocess
to fully run the script in background?
我追加&
到最后是因为otherscript.pl
执行需要一些时间,而且我更喜欢在后台运行。但是,脚本似乎仍然在执行,而没有让我重新控制 shell,我必须等到执行完成才能返回到我的提示。是否有另一种方法可以subprocess
在后台完全运行脚本?
采纳答案by John1024
&
is a shell feature. If you want it to work with subprocess
, you must specify shell=True
like:
&
是外壳功能。如果您希望它与 一起使用subprocess
,则必须指定shell=True
如下:
subprocess.call(command, shell=True)
This will allow you to run command in background.
这将允许您在后台运行命令。
Notes:
笔记:
Since
shell=True
, the above usescommand
, notcommand_list
.Using
shell=True
enables all of the shell's features. Don't do this unlesscommand
includingthingy
comes from sources that you trust.
因为
shell=True
,上述用途command
,不是command_list
。Using
shell=True
启用所有 shell 的功能。除非command
包含thingy
来自您信任的来源,否则不要这样做。
Safer Alternative
更安全的选择
This alternative still lets you run the command in background but is safe because it uses the default shell=False
:
此替代方法仍可让您在后台运行该命令,但它是安全的,因为它使用默认值shell=False
:
p = subprocess.Popen(command_list)
After this statement is executed, the command will run in background. If you want to be sure that it has completed, run p.wait()
.
该语句执行后,该命令将在后台运行。如果您想确保它已完成,请运行p.wait()
.
回答by cucliura
If you want to execute it in Background I recommend you to use nohup
output that would normally go to the terminal goes to a file called nohup.out
如果您想在后台执行它,我建议您使用nohup
通常会转到终端的输出到名为 nohup.out 的文件
import subprocess
subprocess.Popen("nohup usr/local/bin/otherscript.pl {0} >/dev/null 2>&1 &", shell=True)
>/dev/null 2>&1 &
will not create output and will redirect to background
>/dev/null 2>&1 &
不会创建输出并将重定向到后台