문제

I have bunch of modules to import and run. I have dynamically imported the modules using Dynamic module import in Python. This is in the main code. Once imported, I'm trying to run the functions in the modules.

All of the modules look like this structure

#function foo
def run(a,b)
    c=a+b
    return c

foo has been imported, I need to say something like bar=foo.run(a,b) dynamically

from this example: How to call Python functions dynamically. I have already tried the following:

i='foo'

bar = getattr(sys.modules[__name__], i+'.run()')(a,b)

traceback AttributeError: 'module' object has no attribute 'foo.run()'

I'm confused, about the attribute error. The calling functions dynamically example is clearly calling functions.

도움이 되었습니까?

해결책

If you have imported foo already, but don't have a reference to it, use:

sys.modules['foo'].run(a,b)

다른 팁

the_module.run(a, b)

Regardless of what magic made the module come into existence, it's an ordinary module object with ordinary attributes, and you know that the function is called run.

If you always know you'll use module foo, you're done. You may also need to find the module object dynamically, because the module to choose varies. If you imported the module properly, under the name you use to refer to it (e.g. foo) rather than some other name, you can also use sys.modules[mod_name]. Otherwise, you should probably have a dictionary of modules so that you can say, the_module = modules[mod_name].

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top