gpt4 book ai didi

python - 使用 imp 导入模块

转载 作者:行者123 更新时间:2023-11-30 23:27:33 24 4
gpt4 key购买 nike

我有一个执行以下操作的脚本:

import imp
imp.load_source("storage_configuration_reader","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")

稍后,我用相同的名称调用此模块的一个类:

config = storage_configuration_reader()

如果我像上面那样导入它,我会得到以下 NameError NameError: global name 'storage_configuration_reader' is not Defined 但如果我使用以下代码:

import imp
imp.load_source("storage_configuration_reader","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")
import storage_configuration_reader
config = storage_configuration_reader()

然后我收到此错误 TypeError: 'module' object is not callable

更改 imp.load_source 的名称无助于导入对象:

import imp
imp.load_source("storage_configuration","/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.py")
<module 'storage_configuration' from '/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao/storage_configuration_reader.pyc'>
import storage_configuration
config = storage_configuration_reader()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'storage_configuration_reader' is not defined

导入这样的对象的最佳方法(又称工作方法)是哪种?

信息:storage_configuration_reader 定义:

class storage_configuration_reader(object):
"""
Class configuration_reader: this object read the config file and return the
different configuration values
"""
...

最佳答案

imp.load_source 使用给定的path加载模块并使用新的name命名它,它不像from your_module_at_path import your_class_by_name,就像import your_module_at_path as new_name(不完全相同)。

此外,您需要将名称分配给变量才能使用它:

wtf=imp.load_source("new_module_name", your_path)
#wtf is the name you could use directly:
config = wtf.storage_configuration_reader()

名称new_module_name作为键存储在字典sys.modules中,你可以像这样使用它:

sys.modules['new_module_name'].storage_configuration_reader()

从其他目录导入模块的更简单方法是将模块的路径添加到sys.path:

import sys
sys.path.append("/bi/opt/RNAspace/rnaspace_sources/rnaspace/rnaspace/rnaspace/dao")
import storage_configuration_reader
config = storage_configuration_reader.storage_configuration_reader()

关于python - 使用 imp 导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21988781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com