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

2024-05-15 08:53:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我主要是从基函数库中获取示例,以帮助我学习Python。我运行的是linuxmint17,我只想知道基本函数的路径,这样我就可以打开它们并查看它们包含的Python代码。你知道吗


Tags: 函数代码路径示例函数库linuxmint17
2条回答

基本安装通常在/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可能在任何地方,这取决于您在创建virtualenv时指定的内容。使用locate(1)和你的判断。你知道吗

每个非内置模块都有一个__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__'

您还可以使用inspect模块,它有一个.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

相关问题 更多 >