如何找到Python站点包目录的位置?

2024-04-20 13:56:55 发布

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


Tags: python
3条回答
>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

(或仅使用site.getsitepackages()[0]的第一个项)

有两种类型的站点包目录,全局每个用户

  1. Globalsite packages(“dist-packages”)目录在运行时列在sys.path中:

    python -m site
    

    要获得更简洁的列表,请在Python代码中的site module中运行getsitepackages

    python -c "import site; print(site.getsitepackages())"
    

    注意:使用virtualenv sgetsitepackages is not available,上面的sys.path将正确列出virtualenv的站点包目录。

  2. 每个用户的站点包目录(PEP 370)是Python安装本地包的地方:

    python -m site --user-site
    

    如果指向一个不存在的目录,请检查Python的退出状态,并查看python -m site --help以获得解释。

    提示:运行pip list --userpip freeze --user为您提供每个用户站点包的所有已安装的列表。


实用小贴士

  • <package>.__path__用于标识特定包的位置:(details

    $ python -c "import setuptools as _; print(_.__path__)"
    ['/usr/lib/python2.7/dist-packages/setuptools']
    
  • <module>.__file__用于标识特定模块的位置:(difference

    $ python3 -c "import os as _; print(_.__file__)"
    /usr/lib/python3.6/os.py
    
  • 运行pip show <package>以显示Debian样式的包信息:

    $ pip show pytest
    Name: pytest
    Version: 3.8.2
    Summary: pytest: simple powerful testing with Python
    Home-page: https://docs.pytest.org/en/latest/
    Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others
    Author-email: None
    License: MIT license
    Location: /home/peter/.local/lib/python3.4/site-packages
    Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy
    

"How to Install Django" documentation(尽管这不仅对Django安装有用)在shell中执行以下操作:

python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"

格式化为可读性(而不是作为一行代码使用),如下所示:

from distutils.sysconfig import get_python_lib
print(get_python_lib())

相关问题 更多 >