python - 如何让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
...
解决方案
推荐阅读
- linux - 将终端的输出重定向到 libreoffice excel 文件
- javascript - 询问者包,根据以前的答案提出问题
- javascript - 为什么使用 this.get('serviceName') 而不是 this.serviceName?
- terraform - 使用 Terraform/Terragrunt 自动启动/关闭 AMI
- mysql - 没有在 mysql 中修整的 LPAD
- sql - VOLTDB ERROR: SQL ERROR 执行 SQL 时使用了超过 100 MB 的临时表内存
- django - 创建对象时分配给外键字段时的值错误
- python-3.x - Selenium Web 驱动程序 - 尝试单击具有 unselectable="on" 的保存按钮。有没有办法解决这个问题?
- laravel - 从有条件的数据库中获取数据并在视图中显示
- checkstyle - checkstyle 不允许 SuppressWarnings 注释,除非附近有注释