用于预导入模块的Python线程 [英] Python thread for pre-importing modules

查看:126
本文介绍了用于预导入模块的Python线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写科学计算领域的Python应用程序。目前,当用户使用GUI并开始新的物理模拟时,解释器会立即为此模拟导入几个必要的模块,例如 Traits Mayavi的。这些模块很重,导入时间太长,用户必须等待约10秒才可以继续,这很糟糕。

I am writing a Python application in the field of scientific computing. Currently, when the user works with the GUI and starts a new physics simulation, the interpreter immediately imports several necessary modules for this simulation, such as Traits and Mayavi. These modules are heavy and take too long to import, and the user has to wait ~10 seconds before he can continue, which is bad.

我想到了可能的东西解决这个问题。我将描述它,也许其他人已经实现了它,如果是这样,请给我一个链接。如果不是,我可能会自己做。

I thought of something that might remedy this. I'll describe it and perhaps someone else has already implemented it, if so please give me a link. If not I might do it myself.

我想要的是一个单独的线程,它将异步导入模块。它可能是 threading.Thread 的子类。

What I want is a separate thread that will import modules asynchronously. It will probably be a subclass of threading.Thread.

这是一个用法示例:

importer_thread = ImporterThread()
importer_thread.start()

# ...

importer_thread.import('Mayavi')
importer_thread.import('Traits')
# A thread-safe method that will put the module name
# into a queue which the thread in an inifine loop

# ...

# When the user actually needs the modules:
import Mayavi, Traits
# If they were already loaded by importer_thread, we're good.
# If not, we'll just have to wait as usual.

所以你知道这样的事吗?如果没有,你对这个设计有什么建议吗?

So do you know of anything like this? If not, do you have any suggestions about the design?

推荐答案

为什么不在应用程序启动时这样做?

Why not just do this when the app starts?

def background_imports():
    import Traits
    import Mayavi

thread = threading.Thread(target=background_imports)
thread.setDaemon(True)
thread.start()

这篇关于用于预导入模块的Python线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆