在后台执行子进程

Execute Subprocess in Background

我有一个 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)

这将允许您在后台运行命令。

备注:

  1. 因为shell=True,上面用的是command,不是command_list

  2. 使用 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 & 不会创建输出并将重定向到后台