[英]How to call a function of a module by string
I have a module like this 我有一个像这样的模块
# mymodule.py
def myfun():
print "hello"
being called like this 被这样称呼
# main.py
import mymodule
def run(funcname):
mymodule[funcname]()
in a directory structured like this 在这样的目录中
./
|
|--mymodule/
|--__init__.py
|--mymodule.py
|--main.py
When I call the run
method of main.py
like this 当我这样调用
main.py
的run
方法时
run("myfun")
I get this error: 我收到此错误:
TypeError: 'module' object has no attribute '__getitem__'
Understandably. 可以理解。 I wouldve been surprised if this worked.
如果这样做有效,我会感到惊讶。 The thing is, I need to be able to call a method of a module by string.
问题是,我需要能够通过字符串调用模块的方法。 Is this possible?
这可能吗?
Try this. 尝试这个。
def run(funcname):
getattr(mymodule, funcname)()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.