在后台执行子进程

问题描述 投票:8回答:2

我有一个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在后台完全运行脚本吗?

python bash subprocess
2个回答
16
投票

&是一个shell功能。如果你想让它与subprocess一起使用,你必须指定shell=True,如:

subprocess.call(command, shell=True)

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

笔记:

  1. shell=True以来,上面使用command,而不是command_list
  2. 使用shell=True可以实现shell的所有功能。除非包括command在内的thingy来自您信任的来源,否则不要这样做。

Safer Alternative

这个替代方案仍然允许您在后台运行命令,但是安全,因为它使用默认的shell=False

p = subprocess.Popen(command_list)

执行此语句后,该命令将在后台运行。如果你想确保它已经完成,请运行p.wait()


1
投票

如果你想在后台执行它我建议你使用通常去终端的nohup输出转到一个名为nohup.out的文件

import subprocess

subprocess.Popen("nohup usr/local/bin/otherscript.pl {0} >/dev/null 2>&1 &", shell=True)

>/dev/null 2>&1 &不会创建输出并将重定向到背景

© www.soinside.com 2019 - 2024. All rights reserved.