我在哪里可以找到Linux中的python基本函数库?

时间:2014-12-11 15:46:16

标签: python linux

我主要是尝试从基本函数库中获取示例,以帮助我学习Python。我正在运行Linux Mint 17,我想简单地知道基本函数的路径,所以我可以打开它们并查看它们包含的Python代码。

2 个答案:

答案 0 :(得分:2)

每个非内置插件模块都具有__file__属性。他包含加载文件的完整路径,所以如果是在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__'

您也可以使用具有.getsourcefile功能的检查模块,这项工作不仅在模块级别,而且在功能级别也是如此。 如果函数是在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

你有没有看到,如果它是一个外部C库,.getsourcefile什么都不返回。如果它是内置模块/函数/类,则会引发TypeError异常。

.getsourcefile优于__file__的其他优点是,如果函数/类在模块的子文件中声明,则返回正确的文件。您甚至可以在“未知”对象的类型上使用它并执行inspect.getsourcefile(type(obj))

(如果源文件也存在则进行测试,如果加载'.pyc'但是'。py'不存在则返回None

答案 1 :(得分:0)

基本安装通常在/usr/lib{,64}/python*/,并在/usr/lib{,64}/python*/site-packages中安装了包:

ch3ka@x200 /tmp % locate this.py | grep python3\.4
/usr/lib64/python3.4/this.py

(这是模块this的路径 - 用你的python版本替换3\.4,或者只是跳过| grep

但是当使用virtualenv时,你的PYTHONPATH可能在任何地方,取决于你在创建virtualenvs时指定的内容。使用locate(1)和您的判断。