我確定有一個簡單的方法從modulename獲取模塊路徑,對嗎?即我想從path.to.module中檢索/ path/to/module,最好在python 2.7中。從模塊名獲得路徑
我不打算導入模塊,我有modulename作爲字符串。
我確定有一個簡單的方法從modulename獲取模塊路徑,對嗎?即我想從path.to.module中檢索/ path/to/module,最好在python 2.7中。從模塊名獲得路徑
我不打算導入模塊,我有modulename作爲字符串。
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'
>>>
如果您將模塊導入當前命名空間,爲什麼要使用'sys.modules'?只需'藏品'就可以了。 – 2012-03-02 14:12:54
@SvenMarnach,你是對的,但他有模塊路徑,不參考模塊對象 – warvariuc 2012-03-02 14:15:14
那麼,OP同時澄清模塊不應該被導入,所以'sys.modules ['collections']都不是。 __file__'和'collections .__ file__'都不會有幫助。 – 2012-03-02 14:23:07
path = path.to.module.__file__
這是導入模塊後相當容易:
import os
print os.__file__
印在我的機器上
/usr/lib/python2.7/os.pyc
。
爲此導入模塊之前,您可以使用imp.find_module()
:
imp.find_module("os")[1]
這是否柱/回答解決你的問題? http://stackoverflow.com/questions/247770/retrieving-python-module-path – 2012-03-02 14:12:03
我應該在我的問題更清楚,我不打算導入模塊。這篇文章沒有幫助,我以前閱讀過。 – joidegn 2012-03-02 14:19:20