在后台执行子进程

2023-12-28

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

我追加&到最后因为otherscript.pl需要一些时间来执行,我更喜欢在后台运行。但是,该脚本似乎仍然在执行时没有将控制权交还给 shell,而且我必须等到执行完成才能返回提示符。还有其他方法可以使用吗subprocess在后台完全运行脚本?


&是一个外壳功能。如果你想让它与subprocess,您必须指定shell=True like:

subprocess.call(command, shell=True)

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

Notes:

  1. Since shell=True,以上使用command, not command_list.

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

更安全的选择

此替代方案仍然允许您在后台运行该命令,但很安全,因为它使用默认值shell=False:

p = subprocess.Popen(command_list)

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在后台执行子进程 的相关文章

随机推荐