首页 > 解决方案 > 如何让python不多次导入?

问题描述

我的代码有大量导入语句(带有用于调试的打印...):

from __future__ import absolute_import, division, print_function, unicode_literals
import os, sys, struct, json, time, socket
print("start import BS")
from BS import run_BS  # custom library
print("end import BS")
print("Import 1")
print("Import 2")
import numpy as np
print("Import 3")
import platform
import datetime
from posixpath import join as pjoin
print("Import 4")
from multiprocessing import Process, Queue
import matplotlib
import tkinter
print("Import 5")
print("Import 6")
print("Import 7")
from send_tune_request import tune
print("Import  8")
print("Import 9")

代码结构大致是:

class ed_bs:
    def __init__(self, check=False, test_mode=False):
        curr_BS_proc = Process(target=run_BS, args=(a, b, c))
    def main_loop(self):
         while 1:
             pass  # run forever...

if __name__ == '__main__':
    e_d = ed_bs(check=True)
    test_mode = True
    if test_mode:
        test_start_thread = Process(target=tune)
        test_start_thread.setDaemon = True
        test_start_thread.start()

打印语句如下所示:

start import BS
end import BS
Import 1
Import 2
Import 3
Import 4
Import 5
Import 6
Import 7
Import  8
Import 9
start import BS
end import BS
Import 1
Import 2
Import 3
Import 4
Import 5
Import 6
Import 7
Import  8
Import 9
start import BS
end import BS
Import 1
Import 2
Import 3
Import 4
Import 5
Import 6
Import 7
Import  8
Import 9

我猜它打印了 3 次,因为这个流程中有 3 个进程(__main__进程tune、 和run_BS),但是 BS 和 send_tune_request 都没有导入__file__文件,所以我有点困惑。导入需要很长时间(run_BS有 Tensforflow 跟踪编译)并使用大量内存在三个处理器上三次导入所有内容,所以我想更适当地限制导入。

为什么导入需要很长时间?如何让所有内容只导入一次?

谢谢您的帮助。

编辑:BS.py 看起来像下面这样:

from __future__ import absolute_import, division, print_function, unicode_literals
import os, sys, struct, json, time
from posixpath import join as pjoin
from termcolor import colored
import numpy as np
import scipy.signal as sig
import tensorflow as tf
import platform
import tensorflow_probability as tfp

def run_BS():
    bs = BS()
    while 1:
        bs.process_data()

class BS:
    def process_data(self):
        self.tf_process_1()
        self.tf_process_2()
        self.non_tf_process()

    @tf.function
    def tf_process_1(self):
        tf.cast()
        ...

    @tf.function
    def tf_process_2(self):
        tf.cast()
        ...

    def non_tf_process(self):
        x = np.zeros(100)
        x = x+1
        ...

标签: pythonpython-3.xtensorflowpython-import

解决方案


推荐阅读