[英]Unable to access module functions after using importlib.import_module
I am attempting to access some functions in file that's one directory below the file where I want to use them. 我试图访问文件中的一些函数,该文件位于我想要使用它们的文件下面的一个目录中。 I am looking to do this in a dynamic fashion, as I will not know prior to runtime which functions the user will want to use.
我希望以动态的方式做到这一点,因为我不会在运行时之前知道用户想要使用哪些功能。
I will ask the user for a particular scenario, for example, and if they request the 1424 scenario, I would like to have access to functions in a 'scenarios/scenario1424.py' file. 例如,我会询问用户特定场景,如果他们请求1424场景,我想访问'scenario / scenario1424.py'文件中的函数。
I am looking to do this using importlib.import_module(...), but I can't seem to have it let me access those functions even though I seem to be successfully importing the file module. 我希望使用importlib.import_module(...)来做这件事,但我似乎无法让它访问这些功能,即使我似乎成功导入文件模块。
Directory structure: 目录结构:
code/
- main.py
scenarios/
- __init__.py (empty)
- scenario1420.py
- scenario1421.py
- scenario1424.py
Inside a scenario file, I'll have a bunch of methods defined like so: 在场景文件中,我将有一堆定义的方法如下:
def run():
.......
def compute():
.......
I seemed to be able to import the module using importlib.import_module('scenarios.scenario1424')
(returns <module 'scenarios.scenario1424' from 'scenarios/scenario1424.pyc'>
), but when I attempt to access a function like: scenario1424.run()
, I get a NameError ( NameError: name 'scenario1424' is not defined
). 我似乎能够使用
importlib.import_module('scenarios.scenario1424')
导入模块importlib.import_module('scenarios.scenario1424')
<module 'scenarios.scenario1424' from 'scenarios/scenario1424.pyc'>
返回<module 'scenarios.scenario1424' from 'scenarios/scenario1424.pyc'>
importlib.import_module('scenarios.scenario1424')
<module 'scenarios.scenario1424' from 'scenarios/scenario1424.pyc'>
),但当我尝试访问如下函数时: scenario1424.run()
,我得到一个NameError( NameError: name 'scenario1424' is not defined
)。
Any thoughts? 有什么想法吗?
import_module
returns the module object itself, it is your own responsibility to assign it to a name you can use. import_module
返回模块对象本身,您自己负责将其分配给您可以使用的名称。 So in your case it would be 所以在你的情况下它会
scenario1424 = importlib.import_module('scenarios.scenario1424')
Does your subdirectory contain a __init__.py
file? 您的子目录是否包含
__init__.py
文件?
Python uses __init__.py
to determine if a directory is a module. Python使用
__init__.py
来确定目录是否是模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.