下面的代码失败并出现 NameError。代码有什么问题吗?如何在后台线程中导入模块?
import threading
def background_imports():
from time import time
thread = threading.Thread(target=background_imports)
thread.setDaemon(True) # Doesn't make a difference
thread.start()
thread.join()
print(time()) # NameError: name 'time' is not defined
更新:我有在加载时访问 PSQL 的模块。在我的例子中,异步加载模块并没有减少启动时间。
Update2:我对这个问题看到-1。我有什么办法可以改进它吗?
这有效
import threading
import sys
def background_imports():
thismodule = sys.modules[__name__]
module = __import__("time", fromlist=["time"])
attr = getattr(module, "time")
setattr(thismodule, "time", attr)
thread = threading.Thread(target=background_imports)
thread.setDaemon(True)
thread.start()
thread.join()
print(time())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)