Python 在后台执行子流程
我有一个python脚本,它接受一个输入,将其格式化为一个命令,该命令调用服务器上的另一个脚本,然后使用子流程执行:Python 在后台执行子流程,python,bash,subprocess,Python,Bash,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) 我将&附加到末尾,因为执行othe
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
需要一些时间,而且我更喜欢在后台运行。但是,脚本似乎仍然在执行,而没有将控制权交还给shell,我必须等到执行完成后才能返回提示符。是否有其他方法可以使用子流程
在后台完全运行脚本?&
是shell功能。如果希望它与子流程一起工作
,则必须指定shell=True
如下:
subprocess.call(command, shell=True)
这将允许您在后台运行命令
注:
shell=True
,以上使用的是命令
,而不是命令列表
shell=True
启用shell的所有功能。除非命令
包括东西
来自您信任的来源,否则不要这样做shell=False
:
p = subprocess.Popen(command_list)
执行此语句后,该命令将在后台运行。如果您想确保它已完成,请运行
p.wait()
如果您想在后台执行它,我建议您使用nohup
输出,该输出通常会发送到终端,然后发送到名为nohup.out的文件
import subprocess
subprocess.Popen("nohup usr/local/bin/otherscript.pl {0} >/dev/null 2>&1 &", shell=True)
/dev/null 2>&1&
将不创建输出并重定向到后台比直接调用灵活得多
-开销稍大,但它拥有您想要的控制权谢谢!我一直在关注使用Popen的人,但是pydoc详细阐述API的方式非常复杂。比我想象的要简单得多。再次感谢!