问题:如何找到我的Python site-packages目录的位置?

我如何找到我的site-packages目录的位置?

How do I find the location of my site-packages directory?


回答 0

网站包目录有两种类型,全局目录和每个用户目录。

  1. 运行时会列出全局站点软件包(“ dist-packages ”)目录sys.path

    python -m site

    要在Python代码中getsitepackages站点模块运行更简洁的列表,请执行以下操作:

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

    注意:使用virtualenvs时,getsitepackages不可用,但是sys.path从上面将正确列出virtualenv的site-packages目录。在Python 3中,您可以改为使用sysconfig模块

    python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
  2. 每个用户站点包目录(PEP 370)是其中的Python安装本地套餐:

    python -m site --user-site

    如果这指向一个不存在的目录,请检查Python的退出状态并查看python -m site --help说明。

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


实用技巧

  • <package>.__path__可让您识别特定包装的位置:(详细信息

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

    $ 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
    

There are two types of site-packages directories, global and per user.

  1. Global site-packages (“dist-packages“) directories are listed in sys.path when you run:

    python -m site
    

    For a more concise list run getsitepackages from the site module in Python code:

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

    Note: With virtualenvs getsitepackages is not available, sys.path from above will list the virtualenv’s site-packages directory correctly, though. In Python 3, you may use the sysconfig module instead:

    python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
    
  2. The per user site-packages directory (PEP 370) is where Python installs your local packages:

    python -m site --user-site
    

    If this points to a non-existing directory check the exit status of Python and see python -m site --help for explanations.

    Hint: Running pip list --user or pip freeze --user gives you a list of all installed per user site-packages.


Practical Tips

  • <package>.__path__ lets you identify the location(s) of a specific package: (details)

    $ python -c "import setuptools as _; print(_.__path__)"
    ['/usr/lib/python2.7/dist-packages/setuptools']
    
  • <module>.__file__ lets you identify the location of a specific module: (difference)

    $ python3 -c "import os as _; print(_.__file__)"
    /usr/lib/python3.6/os.py
    
  • Run pip show <package> to show Debian-style package information:

    $ 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
    

回答 1

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

(或仅带的第一项site.getsitepackages()[0]

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

(or just first item with site.getsitepackages()[0])


回答 2

解决方案:

  • 在virtualenv外部-提供全局站点程序包的路径,
  • 包含virtualenv-提供virtualenv的站点包

…是单线的:

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

出于可读性考虑而格式化(而不是单行使用),其外观如下所示:

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


资料来源:“如何安装Django”文档的非常旧的版本(尽管这不仅对Django安装有用)

A solution that:

  • outside of virtualenv – provides the path of global site-packages,
  • insidue a virtualenv – provides the virtualenv’s site-packages

…is this one-liner:

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

Formatted for readability (rather than use as a one-liner), that looks like the following:

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


Source: an very old version of “How to Install Django” documentation (though this is useful to more than just Django installation)


回答 3

对于Ubuntu

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

…是不正确的。

它将指向您 /usr/lib/pythonX.X/dist-packages

该文件夹仅包含您的操作系统已自动安装的程序运行包。

在ubuntu上,包含通过setup_tools \ easy_install \ pip安装的软件包的site-packages文件夹位于/usr/local/lib/pythonX.X/dist-packages

如果用例与安装或阅读源代码有关,则第二个文件夹可能更有用。

如果您不使用Ubuntu,则可以安全地将第一个代码框复制粘贴到终端中。

For Ubuntu,

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

…is not correct.

It will point you to /usr/lib/pythonX.X/dist-packages

This folder only contains packages your operating system has automatically installed for programs to run.

On ubuntu, the site-packages folder that contains packages installed via setup_tools\easy_install\pip will be in /usr/local/lib/pythonX.X/dist-packages

The second folder is probably the more useful one if the use case is related to installation or reading source code.

If you do not use Ubuntu, you are probably safe copy-pasting the first code box into the terminal.


回答 4

这对我有用:

python -m site --user-site

This is what worked for me:

python -m site --user-site

回答 5

假设您已经安装了“ django”软件包。导入并输入dir(django)。它将向您显示该模块的所有功能和属性。键入python解释器-

>>> import django
>>> dir(django)
['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version']
>>> print django.__path__
['/Library/Python/2.6/site-packages/django']

如果您已经安装了Mercurial,则可以执行相同的操作。

这是给雪豹的。但我认为它通常也应该起作用。

Let’s say you have installed the package ‘django’. import it and type in dir(django). It will show you, all the functions and attributes with that module. Type in the python interpreter –

>>> import django
>>> dir(django)
['VERSION', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'get_version']
>>> print django.__path__
['/Library/Python/2.6/site-packages/django']

You can do the same thing if you have installed mercurial.

This is for Snow Leopard. But I think it should work in general as well.


回答 6

如其他人所述,distutils.sysconfig具有相关设置:

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

…尽管默认值的site.py含义有些粗略,如下所述:

import sys, os
print os.sep.join([sys.prefix, 'lib', 'python' + sys.version[:3], 'site-packages'])

(如果该常量不同,它还会添加${sys.prefix}/lib/site-python和添加两条路径sys.exec_prefix)。

也就是说,背景是什么?您不应该site-packages直接与自己混为一谈。setuptools / distutils将可以进行安装,并且您的程序可能在virtualenv中运行,其中pythonpath完全是用户本地的,因此也不应假定直接使用系统站点包。

As others have noted, distutils.sysconfig has the relevant settings:

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

…though the default site.py does something a bit more crude, paraphrased below:

import sys, os
print os.sep.join([sys.prefix, 'lib', 'python' + sys.version[:3], 'site-packages'])

(it also adds ${sys.prefix}/lib/site-python and adds both paths for sys.exec_prefix as well, should that constant be different).

That said, what’s the context? You shouldn’t be messing with your site-packages directly; setuptools/distutils will work for installation, and your program may be running in a virtualenv where your pythonpath is completely user-local, so it shouldn’t assume use of the system site-packages directly either.


回答 7

现代的stdlib方法是使用sysconfig模块,该模块在2.7和3.2+版本中可用。

sysconfig)不与混淆distutils.sysconfig子模块(在其他几个答案这里提到)。后者是一个完全不同的模块,缺少get_paths下面讨论的功能。

Python当前使用八个路径(docs):

  • stdlib:包含非平台特定标准Python库文件的目录。
  • platstdlib:包含特定于平台的标准Python库文件的目录。
  • platlib:特定于站点,特定于平台的文件的目录。
  • purelib:特定于站点的,非特定于平台的文件的目录。
  • include:非平台特定头文件的目录。
  • platinclude:特定于平台的头文件的目录。
  • scripts:脚本文件的目录。
  • data:数据文件目录。

在大多数情况下,发现此问题的用户会对“ purelib”路径感兴趣(在某些情况下,您可能也对“ platlib”感兴趣)。与当前接受的答案不同,无论您是否激活了virtualenv,该方法仍然有效。

在系统级别(在Mac OS上为Python 3.7.0):

>>> import sysconfig
>>> sysconfig.get_paths()['purelib']
'/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'

有了静脉,你会得到这样的东西

>>> import sysconfig
>>> sysconfig.get_paths()['purelib']
'/private/tmp/.venv/lib/python3.7/site-packages'

还可以使用Shell脚本来显示这些详细信息,您可以通过将其sysconfig作为模块执行来调用这些详细信息:

python -m sysconfig

A modern stdlib way is using sysconfig module, available in version 2.7 and 3.2+.

Note: sysconfig (source) is not to be confused with the distutils.sysconfig submodule (source) mentioned in several other answers here. The latter is an entirely different module and it’s lacking the get_paths function discussed below.

Python currently uses eight paths (docs):

  • stdlib: directory containing the standard Python library files that are not platform-specific.
  • platstdlib: directory containing the standard Python library files that are platform-specific.
  • platlib: directory for site-specific, platform-specific files.
  • purelib: directory for site-specific, non-platform-specific files.
  • include: directory for non-platform-specific header files.
  • platinclude: directory for platform-specific header files.
  • scripts: directory for script files.
  • data: directory for data files.

In most cases, users finding this question would be interested in the ‘purelib’ path (in some cases, you might be interested in ‘platlib’ too). Unlike the current accepted answer, this method still works regardless of whether or not you have a virtualenv activated.

At system level (this is Python 3.7.0 on mac OS):

>>> import sysconfig
>>> sysconfig.get_paths()['purelib']
'/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'

With a venv, you’ll get something like this

>>> import sysconfig
>>> sysconfig.get_paths()['purelib']
'/private/tmp/.venv/lib/python3.7/site-packages'

A shell script is also available to display these details, which you can invoke by executing sysconfig as a module:

python -m sysconfig

回答 8

在基于Debian的系统中随python安装一起安装的本机系统软件包可以在以下位置找到:

/usr/lib/python2.7/dist-packages/

在OSX中- /Library/Python/2.7/site-packages

通过使用此小代码:

from distutils.sysconfig import get_python_lib
print get_python_lib()

但是,pip可以在以下位置找到通过安装的软件包列表:

/ usr / local / bin /

或者,只需编写以下命令即可列出python软件包所在的所有路径。

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

注意:位置可能会因您的操作系统而异,例如在OSX中

>>> import site; site.getsitepackages()
['/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/site-python', '/Library/Python/2.7/site-packages']

The native system packages installed with python installation in Debian based systems can be found at :

/usr/lib/python2.7/dist-packages/

In OSX – /Library/Python/2.7/site-packages

by using this small code :

from distutils.sysconfig import get_python_lib
print get_python_lib()

However, the list of packages installed via pip can be found at :

/usr/local/bin/

Or one can simply write the following command to list all paths where python packages are.

>>> import site; site.getsitepackages()
['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

Note: the location might vary based on your OS, like in OSX

>>> import site; site.getsitepackages()
['/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/site-python', '/Library/Python/2.7/site-packages']

回答 9

所有答案(或:一遍又一遍重复的相同答案)都不够。您要做的是:

from setuptools.command.easy_install import easy_install
class easy_install_default(easy_install):
  """ class easy_install had problems with the fist parameter not being
      an instance of Distribution, even though it was. This is due to
      some import-related mess.
      """

  def __init__(self):
    from distutils.dist import Distribution
    dist = Distribution()
    self.distribution = dist
    self.initialize_options()
    self._dry_run = None
    self.verbose = dist.verbose
    self.force = None
    self.help = 0
    self.finalized = 0

e = easy_install_default()
import distutils.errors
try:
  e.finalize_options()
except distutils.errors.DistutilsError:
  pass

print e.install_dir

最后一行显示安装目录。可在Ubuntu上使用,而以上版本则不能。不要问我有关Windows或其他dists的问题,但是由于它与easy_install默认使用的目录完全相同,因此在easy_install工作的所有地方(所以,甚至是macs),它都可能是正确的。玩得开心。注意:原始代码中包含许多脏话。

All the answers (or: the same answer repeated over and over) are inadequate. What you want to do is this:

from setuptools.command.easy_install import easy_install
class easy_install_default(easy_install):
  """ class easy_install had problems with the fist parameter not being
      an instance of Distribution, even though it was. This is due to
      some import-related mess.
      """

  def __init__(self):
    from distutils.dist import Distribution
    dist = Distribution()
    self.distribution = dist
    self.initialize_options()
    self._dry_run = None
    self.verbose = dist.verbose
    self.force = None
    self.help = 0
    self.finalized = 0

e = easy_install_default()
import distutils.errors
try:
  e.finalize_options()
except distutils.errors.DistutilsError:
  pass

print e.install_dir

The final line shows you the installation dir. Works on Ubuntu, whereas the above ones don’t. Don’t ask me about windows or other dists, but since it’s the exact same dir that easy_install uses by default, it’s probably correct everywhere where easy_install works (so, everywhere, even macs). Have fun. Note: original code has many swearwords in it.


回答 10

旁注:distutils.sysconfig.get_python_lib()如果存在多个site-packages目录(如本文推荐),则建议的解决方案()不起作用。它只会返回主site-packages目录。

,我也没有更好的解决方案。Python似乎不跟踪站点软件包目录,而只是跟踪其中的软件包。

A side-note: The proposed solution (distutils.sysconfig.get_python_lib()) does not work when there is more than one site-packages directory (as recommended by this article). It will only return the main site-packages directory.

Alas, I have no better solution either. Python doesn’t seem to keep track of site-packages directories, just the packages within them.


回答 11

这对我有用。这将使您同时获得dist-packages和site-packages文件夹。如果该文件夹不在Python的路径上,则无论如何都不会给您带来什么好处。

import sys; 
print [f for f in sys.path if f.endswith('packages')]

输出(Ubuntu安装):

['/home/username/.local/lib/python2.7/site-packages',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages']

This works for me. It will get you both dist-packages and site-packages folders. If the folder is not on Python’s path, it won’t be doing you much good anyway.

import sys; 
print [f for f in sys.path if f.endswith('packages')]

Output (Ubuntu installation):

['/home/username/.local/lib/python2.7/site-packages',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages']

回答 12

由于它具有“低技术”性质,因此该方法适用于虚拟环境内外的所有发行版。os模块始终位于“ site-packages”的父目录中

import os; print(os.path.dirname(os.__file__) + '/site-packages')

要将目录更改为站点程序包目录,我使用以下别名(在* nix系统上):

alias cdsp='cd $(python -c "import os; print(os.path.dirname(os.__file__))"); cd site-packages'

This should work on all distributions in and out of virtual environment due to it’s “low-tech” nature. The os module always resides in the parent directory of ‘site-packages’

import os; print(os.path.dirname(os.__file__) + '/site-packages')

To change dir to the site-packages dir I use the following alias (on *nix systems):

alias cdsp='cd $(python -c "import os; print(os.path.dirname(os.__file__))"); cd site-packages'

回答 13

get_python_lib已经提到的功能的附加说明:在某些平台上,不同的目录用于平台特定的模块(例如:需要编译的模块)。如果传递plat_specific=True给该函数,则将获得针对特定平台的软件包的站点软件包。

An additional note to the get_python_lib function mentioned already: on some platforms different directories are used for platform specific modules (eg: modules that require compilation). If you pass plat_specific=True to the function you get the site packages for platform specific packages.


回答 14

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

回答 15

点子显示将提供有关软件包的所有详细信息:https : //pip.pypa.io/en/stable/reference/pip_show/ [点子显示] [1]

获取位置:

pip show <package_name>| grep Location

pip show will give all the details about a package: https://pip.pypa.io/en/stable/reference/pip_show/ [pip show][1]

To get the location:

pip show <package_name>| grep Location

回答 16

回答老问题。但是为此使用ipython。

pip install ipython
ipython 
import imaplib
imaplib?

这将给出有关imaplib软件包的以下输出-

Type:        module
String form: <module 'imaplib' from '/usr/lib/python2.7/imaplib.py'>
File:        /usr/lib/python2.7/imaplib.py
Docstring:  
IMAP4 client.

Based on RFC 2060.

Public class:           IMAP4
Public variable:        Debug
Public functions:       Internaldate2tuple
                        Int2AP
                        ParseFlags
                        Time2Internaldate

Answer to old question. But use ipython for this.

pip install ipython
ipython 
import imaplib
imaplib?

This will give the following output about imaplib package –

Type:        module
String form: <module 'imaplib' from '/usr/lib/python2.7/imaplib.py'>
File:        /usr/lib/python2.7/imaplib.py
Docstring:  
IMAP4 client.

Based on RFC 2060.

Public class:           IMAP4
Public variable:        Debug
Public functions:       Internaldate2tuple
                        Int2AP
                        ParseFlags
                        Time2Internaldate

回答 17

您应该尝试使用此命令来确定pip的安装位置

Python 2

pip show six | grep "Location:" | cut -d " " -f2

Python 3

pip3 show six | grep "Location:" | cut -d " " -f2

You should try this command to determine pip’s install location

Python 2

pip show six | grep "Location:" | cut -d " " -f2

Python 3

pip3 show six | grep "Location:" | cut -d " " -f2

回答 18

我必须为正在处理的项目做些不同的事情:找到相对于基本安装前缀的相对 site-packages目录。如果site-packages文件夹位于中/usr/lib/python2.7/site-packages,则需要该/lib/python2.7/site-packages部件。我有,事实上,遇到在那里系统site-packages/usr/lib64和公认的答案没有对这些系统的工作。

与作弊者的答案类似,我的解决方案深入探究了Distutils的精髓,以发现实际上在内部传递的路径setup.py。弄清楚这真是太痛苦了,我不想让任何人不得不再次弄清楚这一点。

import sys
import os
from distutils.command.install import INSTALL_SCHEMES

if os.name == 'nt':
    scheme_key = 'nt'
else:
    scheme_key = 'unix_prefix'

print(INSTALL_SCHEMES[scheme_key]['purelib'].replace('$py_version_short', (str.split(sys.version))[0][0:3]).replace('$base', ''))

那应该打印类似/Lib/site-packages或的内容/lib/python3.6/site-packages

I had to do something slightly different for a project I was working on: find the relative site-packages directory relative to the base install prefix. If the site-packages folder was in /usr/lib/python2.7/site-packages, I wanted the /lib/python2.7/site-packages part. I have, in fact, encountered systems where site-packages was in /usr/lib64, and the accepted answer did NOT work on those systems.

Similar to cheater’s answer, my solution peeks deep into the guts of Distutils, to find the path that actually gets passed around inside setup.py. It was such a pain to figure out that I don’t want anyone to ever have to figure this out again.

import sys
import os
from distutils.command.install import INSTALL_SCHEMES

if os.name == 'nt':
    scheme_key = 'nt'
else:
    scheme_key = 'unix_prefix'

print(INSTALL_SCHEMES[scheme_key]['purelib'].replace('$py_version_short', (str.split(sys.version))[0][0:3]).replace('$base', ''))

That should print something like /Lib/site-packages or /lib/python3.6/site-packages.


回答 19

如果已将其添加到中,则PYTHONPATH还可以执行类似操作

import sys
print('\n'.join(sys.path))

If it is already added to the PYTHONPATH you can also do something like

import sys
print('\n'.join(sys.path))

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。