在后台执行子进程

dbi*_*hop 10 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)
Run Code Online (Sandbox Code Playgroud)

我追加&到最后因为otherscript.pl需要一些时间来执行,我更喜欢在后台运行.但是,脚本似乎仍然执行而没有让我重新控制shell,我必须等到执行完成后才能回到我的提示符.有没有其他方法可以subprocess在后台完全运行脚本?

Joh*_*024 18

&是一个shell功能.如果您希望它可以使用subprocess,您必须指定shell=True如下:

subprocess.call(command, shell=True)
Run Code Online (Sandbox Code Playgroud)

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

笔记:

  1. 因为shell=True,以上用途command,不是command_list.

  2. 使用shell=True启用所有shell的功能.除非command包含thingy来自您信任的来源,否则请勿这样做.

更安全的选择

此替代方法仍然允许您在后台运行该命令但是安全,因为它使用默认值shell=False:

p = subprocess.Popen(command_list)
Run Code Online (Sandbox Code Playgroud)

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

  • 这次真是万分感谢!我总是看着使用Popen的人,但是pydoc对API的阐述方式只是如此充满和令人费解.比我想象的要简单得多.再次感谢! (3认同)

小智 7

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

import subprocess

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

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