[英]error dynamically importing and calling module in python 2.7
I'm having trouble getting the two following examples to work together, dynamically loading a module and calling a function by string . 我无法让以下两个示例协同工作, 动态加载模块并按字符串调用函数 。 I'm trying to dynamically load and call python modules.
我正在尝试动态加载和调用python模块。
My file structure is as follows 我的文件结构如下
src/
main.py
__init__.py
modules/
__init__.py
module1.py
module2.py
...
module100.py
In my main.py function I have the following to load the module, 在我的main.py函数中,我有以下内容来加载模块,
mod = imp.load_source('module', '/path/to/module.py')
This seems to be working fine, print module
yields 这似乎工作正常,
print module
产量
<module 'module' from '/path/to/module.py'>
In module.py
I have 在
module.py
我有
class module:
def __init__(self):
print ("HELLO WORLD")
def calc(self):
print ("calc called")
if __name__ == "__main__":
import sys
sys.exit(not main(sys.argv))
The problem is when I try to call the calc function in module, 问题是当我尝试在模块中调用calc函数时,
result = getattr(module, 'calc')()
yields the following 产生以下结果
HELLO WORLD
Traceback (most recent call last):
File "main.py", line 39, in main
result = getattr(module, 'calc')()
AttributeError: 'module' object has no attribute 'calc
I'm not sure what i'm missing or doing wrong 我不确定我错过了什么或做错了什么
For some reason you named your class module
too, which is confusing you. 出于某种原因,你也将你的类
module
命名为,这让你感到困惑。
Your module
is, well, a module: 你的
module
是一个模块:
>>> mod = imp.load_source('module', 'module.py')
>>> mod
<module 'module' from 'module.pyc'>
>>> dir(mod)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'module']
Your class is mod.module
: 你的类是
mod.module
:
>>> x = mod.module()
HELLO WORLD
>>> x
<module.module instance at 0xa1cb18c>
>>> type(x)
<type 'instance'>
Aside: the line 旁白:线
self
doesn't do anything, and your calc
method will need to accept an argument, or you'll get TypeError: calc() takes no arguments (1 given)
when you call it. 什么都不做,你的
calc
方法需要接受一个参数,否则你会得到TypeError: calc() takes no arguments (1 given)
在你调用它时TypeError: calc() takes no arguments (1 given)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.