Python之inspect模块实现获取加载模块路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/laozhuxinlu/article/details/70289135

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 查看结果如下:

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可以截取出单纯的路径。


 

猜你喜欢

转载自blog.csdn.net/laozhuxinlu/article/details/70289135
今日推荐