由于导入,在 python 程序中使用 bash 脚本运行 python 代码时存在高延迟

问题描述 投票:0回答:1

我有一个 python 应用程序,它使用子进程来运行 bash 脚本。 bash 脚本依次运行一个 python 文件,其中包含一些导入(视网膜面部、深层面部库)。该应用程序需要花费大量时间来运行,因为每次运行子进程时,都需要 20-30 秒来加载/导入视网膜/深脸模块。有什么办法可以加快速度吗?

注意:更改设置是不可能的,即我无法直接从原始 python 代码调用 python 代码。

我不确定如何解决这个问题,感谢任何帮助。谢谢你。

我尝试使用系统模块的缓存版本,但这不起作用。虽然,我不确定如何正确使用它。

python machine-learning tkinter module subprocess
1个回答
1
投票

一种方法是加载一次包含大量导入的 Python 文件并保持打开状态。然后,每次 Bash 脚本运行时,它都可以向已经运行的脚本发送一条消息以开始处理。

要与 Bash 中正在运行的 Python 脚本进行通信,有多种方法。一种简单而灵活的方法可能是使用命名管道。这是一种特殊类型的文件,当您读取它时,它会导致 Python 等待输入。

以下内容基于https://stackoverflow.com/a/55734712/

import pathlib
import os
# heavy imports here

FIFO = 'myfifo'
# remove pipe in case it exists
pathlib.Path(FIFO).unlink(missing_ok=True)
# create new pipe
os.mkfifo(FIFO)

def do_something(msg):
    print(f"open {msg} and process it")

while True:
    with open(FIFO) as fifo:
        for line in fifo:
            msg = line.strip()
            do_something(msg)

现在您可以从 Bash 写入管道。确保 Bash 脚本与 Python 脚本具有相同的工作目录,或提供管道的完整路径。请注意,您需要使用

\n
明确结束该行。

printf "somefile.jpg\n" > myfifo

这会导致 Python 脚本打印

open somefile.jpg and process it

然后

while True
循环导致脚本等待进一步的输入。

© www.soinside.com 2019 - 2024. All rights reserved.