问题描述
我有一个python脚本,它接受输入,将其格式化为命令,该命令调用服务器上的另一个脚本,然后使用子进程执行:
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:
import sys, subprocess
thingy = sys.argv[1]
command = 'usr/local/bin/otherscript.pl {0} &'.format(thingy)
command_list = command.split()
subprocess.call(command_list)
我将&
附加到末尾,因为otherscript.pl
需要花费一些时间来执行,并且我更喜欢在后台运行.但是,该脚本似乎仍在执行,而没有将控制权交还给我,因此我必须等到执行完成才能返回到提示符.有没有其他方法可以使用subprocess
在后台完全运行脚本?
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?
推荐答案
&
是shell功能.如果您希望它与subprocess
一起使用,则必须指定shell=True
,例如:
&
is a shell feature. If you want it to work with subprocess
, you must specify shell=True
like:
subprocess.call(command, shell=True)
这将允许您在后台运行命令.
This will allow you to run command in background.
注意:
-
自
shell=True
起,以上使用了command
,而不是command_list
.
Since
shell=True
, the above usescommand
, notcommand_list
.
使用shell=True
启用Shell的所有功能.除非command
包括thingy
来自您信任的来源,否则不要这样做.
Using shell=True
enables all of the shell's features. Don't do this unless command
including thingy
comes from sources that you trust.
更安全的选择
此替代方法仍然可以让您在后台运行命令,但安全,因为它使用默认的shell=False
:
p = subprocess.Popen(command_list)
执行该语句后,该命令将在后台运行.如果要确保已完成,请运行p.wait()
.
After this statement is executed, the command will run in background. If you want to be sure that it has completed, run p.wait()
.
这篇关于在后台执行子流程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!