在后台执行子进程

2023-07-21Python开发问题
2

本文介绍了在后台执行子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

这篇关于在后台执行子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10