我有一个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)
我追加&
到底,因为otherscript.pl
需要一些时间来执行,我更喜欢在后台运行。但是,脚本似乎仍然执行而没有让我重新控制shell,我必须等到执行完成后才能回到我的提示符。还有另一种方法可以使用subprocess
在后台完全运行脚本吗?
&
是一个shell功能。如果你想让它与subprocess
一起使用,你必须指定shell=True
,如:
subprocess.call(command, shell=True)
这将允许您在后台运行命令。
笔记:
shell=True
以来,上面使用command
,而不是command_list
。shell=True
可以实现shell的所有功能。除非包括command
在内的thingy
来自您信任的来源,否则不要这样做。这个替代方案仍然允许您在后台运行命令,但是安全,因为它使用默认的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 &
不会创建输出并将重定向到背景