从Python dir()调用模块
发布时间:2021-02-20 20:30:04 所属栏目:Python 来源:互联网
导读:简短的问题 是否可以调用从 python dir()函数检索的模块? 背景 我正在构建一个自定义测试运行器,并希望能够根据字符串过滤器选择要运行的模块.有关理想用法,请参阅下面的示例. module_a.py def not_mykey_dont_do_this(): print I better not do thisdef myk
简短的问题
背景 module_a.py def not_mykey_dont_do_this(): print 'I better not do this' def mykey_do_something(): print 'Doing something!' def mykey_do_somethingelse(): print 'Doing something else!' module_b.py import module_a list_from_a = dir(module_a) # ['not_mykey_dont_do_this','mykey_do_something','mykey_do_somethingelse'] for mod in list_from_a: if(mod.startswith('mykey_'): # Run the module module_a.mod() # Note that this will *not* work because 'mod' is a string 产量 Doing something! Doing something else! 解决方法getattr(module_a,mod)() getattr是一个内置函数,它接受对象和字符串,并返回属性. (编辑:台州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- __del__上的Python attributeError
- python-2.7 – 无法安装PythonMagick Windows 7
- python3 requests中使用ip代理池随机生成ip的实例
- python – 展开并合并Pandas数据帧
- python – 最终确保一些代码以原子方式运行,无论如何?
- python – 用于Django项目/应用程序的RESTful API
- python – paramiko没有现有的会话异常
- python:re.sub的replace函数不接受额外的参数 – 如何避免
- Python Pandas:如果数据是NaN,则更改为0,否则在数据框中更
- python – 分类:使用sklearn进行PCA和逻辑回归