适用于点分模块的`imp.find_module`版本
有没有一个已经存在的实现,可以让我们用带点的模块名称来使用imp.find_module
?这个实现不需要完美无缺,能处理一些情况就可以了。如果能处理的情况越多,那就越好。
另外,请不要在回答里尝试实现这个功能。我已经写了自己的版本,我在问是否有一个已经存在的实现,因为如果有的话,可能比我的版本经过了更多的测试。
5 个回答
1
def find_dotted_module(name, path=None):
'''
Example: find_dotted_module('mypackage.myfile')
Background: imp.find_module() does not handle hierarchical module names (names containing dots).
Important: No code of the module gets executed. The module does not get loaded (on purpose)
ImportError gets raised if the module can't be found.
Use case: Test discovery without loading (otherwise coverage does not see the lines which are executed
at import time)
'''
for x in name.split('.'):
if path is not None:
path=[path]
file, path, descr = imp.find_module(x, path)
return path
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
1
对于其他查看这个问题并寻找方法的人,这里是我正在使用的内容。
import imp
def find_dotted_module(name, path=None):
res = None
for x in name.split('.'):
res = imp.find_module(x, path)
path = [module[1]]
return res