简体   繁体   中英

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.

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,

mod = imp.load_source('module', '/path/to/module.py')

This seems to be working fine, print module yields

<module 'module' from '/path/to/module.py'>

In module.py I have

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,

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.

Your module is, well, a 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 :

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM