Python之inspect子產品實作擷取加載子產品路徑
該文主要介紹如何擷取子產品的路徑,需要申明的是這裡所說的子產品可以是功能實作的該子產品,也可以是别的子產品。
使用到的是 inspect 子產品的 .getsourcefile(需要擷取的子產品名)
建立test.py内容如下:
import os
import 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 檢視結果如下:
[email protected]:~/Desktop/python$ python test.py
/usr/local/lib/python2.7/os.py
('/usr/local/lib/python2.7', 'os.py')
[email protected]:~/Desktop/python$
可以看到我們直接擷取到了 :/usr/local/lib/python2.7/os.py , 通過 os.path.split可以截取出單純的路徑。