Python 在后台执行子进程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32577071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:50:26  来源:igfitidea点击:

Execute Subprocess in Background

pythonbashsubprocess

提问by dbishop

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:

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

I append &to the end because otherscript.pltakes 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 subprocessto fully run the script in background?

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

采纳答案by John1024

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

&是外壳功能。如果您希望它与 一起使用subprocess,则必须指定shell=True如下:

subprocess.call(command, shell=True)

This will allow you to run command in background.

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

Notes:

笔记:

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

  2. Using shell=Trueenables all of the shell's features. Don't do this unless commandincluding thingycomes from sources that you trust.

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

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

Safer Alternative

更安全的选择

This alternative still lets you run the command in background but is safe because it uses the default shell=False:

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

p = subprocess.Popen(command_list)

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

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

回答by cucliura

If you want to execute it in Background I recommend you to use nohupoutput that would normally go to the terminal goes to a file called nohup.out

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

import subprocess

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

>/dev/null 2>&1 &will not create output and will redirect to background

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