在后台执行子进程

2022-01-18 00:00:00 python subprocess bash

问题描述

我有一个 python 脚本,它接受输入,将其格式化为调用服务器上另一个脚本的命令,然后使用子进程执行:

I have a python script which takes an input, formats it into a command which calls another script on the server, and then executes using subprocess:

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

I append & to the end because otherscript.pl takes some time to execute, and I prefer to have run in the background. However, the script still seems to execute without giving me back control to the shell, and I have to wait until execution finishes to get back to my prompt. Is there another way to use subprocess to fully run the script in background?


解决方案

& 是一个 shell 功能.如果您希望它与 subprocess 一起使用,则必须指定 shell=True,例如:

& is a shell feature. If you want it to work with subprocess, you must specify shell=True like:

subprocess.call(command, shell=True)

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

This will allow you to run command in background.

注意事项:

  1. 由于shell=True,以上使用的是command,而不是command_list.

  1. Since shell=True, the above uses command, not command_list.

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

Using shell=True enables all of the shell's features. Don't do this unless command including thingy comes from sources that you trust.

更安全的选择

此替代方法仍可让您在后台运行命令,但很安全,因为它使用默认的 shell=False:

p = subprocess.Popen(command_list)

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

After this statement is executed, the command will run in background. If you want to be sure that it has completed, run p.wait().

相关文章