问题描述
我有一个 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.
注意事项:
由于
shell=True,以上使用的是command,而不是command_list.
Since
shell=True, the above usescommand, notcommand_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().
这篇关于在后台执行子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)