該文主要介紹如何獲取模塊的路徑,需要申明的是這里所說的模塊可以是功能實現的該模塊,也可以是別的模塊。
使用到的是 inspect 模塊的 .getsourcefile(需要獲取的模塊名)
創建test.py內容如下:
import osimport inspect class pathManager(object): def __init__(self): pass def _abPath(self): modulePath = inspect.getsourcefile(os) abPath = os.path.split(modulePath) return abPath[0] if __name__ == "__main__": getPath = pathManager() getPath._abPath()
執行 python test.py 查看結果如下:
clay@aclgcl-ubnt:~/Desktop/python$ python test.py /usr/local/lib/python2.7/os.py('/usr/local/lib/python2.7', 'os.py')clay@aclgcl-ubnt:~/Desktop/python$
可以看到我們直接獲取到了 :/usr/local/lib/python2.7/os.py , 通過 os.path.split可以截取出單純的路徑。
以上這篇Python之inspect模塊實現獲取加載模塊路徑的方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答