在后台执行子进程

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

问题描述

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)