>>> import collections # from the std lib in pure python
>>> collections.__file__
'/usr/lib/python2.7/collections.pyc'
>>> import datetime # from the std lib as a C module
>>> datetime.__file__
'/usr/lib/python2.7/lib-dynload/datetime.so'
>>> import itertools # from the std lib but a built-in module
>>> itertools.__file__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__file__'
>>> import inspect
>>> inspect.getsourcefile(collections) # Pure python
'/usr/lib/python2.7/collections.py'
>>> inspect.getsourcefile(collections.namedtuple) # Work with a function too.
'/usr/lib/python2.7/collections.py'
>>> inspect.getsourcefile(datetime) # C module so it will return just None
>>> inspect.getsourcefile(itertools) # Built-in so it raise an exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/inspect.py", line 444, in getsourcefile
filename = getfile(object)
File "/usr/lib/python2.7/inspect.py", line 403, in getfile
raise TypeError('{!r} is a built-in module'.format(object))
TypeError: <module 'itertools' (built-in)> is a built-in module
基本安装通常在
/usr/lib{,64}/python*/
,安装包在/usr/lib{,64}/python*/site-packages
:(这是模块
this
的路径-用python版本替换3\.4
,或者跳过| grep
)但是在使用virtualenv时,PYTHONPATH可能在任何地方,这取决于您在创建virtualenv时指定的内容。使用
locate(1)
和你的判断。你知道吗每个非内置模块都有一个
__file__
属性。他包含加载文件的完整路径,因此如果是用python编写的模块,您将得到一个“.pyc”文件,如果是C模块,“.so”。你知道吗您还可以使用inspect模块,它有一个
.getsourcefile
函数,这不仅在模块级工作,而且在函数级工作。如果函数是用python声明的!您可以看到,如果它是一个外部C库,
.getsourcefile
不返回任何内容。如果它是一个内置模块/函数/类,它会引发TypeError
异常。你知道吗.getsourcefile
优于__file__
的其他优点是,如果函数/类在模块的子文件中声明,它将返回正确的文件。您甚至可以在“未知”对象的类型上使用它并执行inspect.getsourcefile(type(obj))
。你知道吗(测试源文件是否也存在,如果加载了'.pyc',但'.py'不存在,则返回
None
)相关问题 更多 >
编程相关推荐