Linux中python基函数库的位置在哪里?
我主要尝试从基本函数库中获取示例,以帮助我学习Python。我正在运行Linux Mint 17,我只想知道基本函数的路径,这样我就可以打开它们并查看它们包含的Python代码。基本安装通常在Linux中python基函数库的位置在哪里?,python,linux,Python,Linux,我主要尝试从基本函数库中获取示例,以帮助我学习Python。我正在运行Linux Mint 17,我只想知道基本函数的路径,这样我就可以打开它们并查看它们包含的Python代码。基本安装通常在/usr/lib{,64}/Python*/中,安装包在/usr/lib{,64}/Python*/站点包中: ch3ka@x200 /tmp % locate this.py | grep python3\.4 /usr/lib64/python3.4/this.py (这是模块this-用python
/usr/lib{,64}/Python*/
中,安装包在/usr/lib{,64}/Python*/站点包中
:
ch3ka@x200 /tmp % locate this.py | grep python3\.4
/usr/lib64/python3.4/this.py
(这是模块this
-用python版本替换3\.4
,或直接跳过|grep
)
但是当使用virtualenv时,PYTHONPATH可能在任何地方,这取决于您在创建virtualenv时指定的内容。使用
locate(1)
和您的判断。每个非内置模块都有一个\uuuuuuuuu文件
属性。他包含加载文件的完整路径,因此,如果是用python编写的模块,您将得到一个“.pyc”文件,如果是C模块,则得到一个“.so”
>>> 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__'
您可以看到,如果它是一个外部C库,.getsourcefile
不返回任何内容。如果它是内置模块/函数/类,则会引发TypeError
异常
.getsourcefile
优于\uuuuuuuuuuuuuuuuu
的其他优点是,如果函数/类在模块的子文件中声明,它将返回正确的文件。您甚至可以在“未知”对象的类型上使用它,并执行inspect.getsourcefile(type(obj))
(测试源文件是否也存在,如果加载了“.pyc”但“.py”不存在,则返回
None
)内置函数,如len
和id
?我认为这些都不是用Python编写的。
>>> 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