从模块名称获取路径

joi*_*egn 4 python python-2.7

我确定有一种从模块名称获取模块路径的简单方法,对吧?即我想从path.to.module中检索/ path/to/module,最好是在python 2.7中.

我不打算导入模块,我将模块名称作为字符串.

Sve*_*ach 10

导入模块后,这很容易:

import os
print os.__file__
Run Code Online (Sandbox Code Playgroud)

版画

/usr/lib/python2.7/os.pyc
Run Code Online (Sandbox Code Playgroud)

在我的机器上.

导入模块之前执行此操作,您可以使用imp.find_module():

imp.find_module("os")[1]
Run Code Online (Sandbox Code Playgroud)


war*_*iuc 6

sys.modules['path.to.module'].__file__

Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import collections
>>> import sys
>>> sys.modules['collections'].__file__
'/usr/lib/python2.7/collections.pyc'
>>>
Run Code Online (Sandbox Code Playgroud)

  • 那么,OP同时澄清了该模块根本不应该导入,因此`sys.modules ['collections'] .__ file__`和`collections .__ file__`都不会有帮助. (2认同)