1374

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

Yuri
  • 4,254
  • 1
  • 29
  • 46
Daryl Spitzer
  • 143,156
  • 76
  • 154
  • 173

22 Answers22

1047

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())'
    

    Caution: In virtual environments getsitepackages is not available with older versions of virtualenv, 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
    
Peterino
  • 15,097
  • 3
  • 28
  • 29
  • 26
    there is a site package directory in a virtualenv. You can get the directory for site-specific modules inside/outside virtualenv using [`python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"`](https://stackoverflow.com/a/122340/4279) (it works on both Python 2 and 3 too). – jfs Sep 13 '17 at 14:15
  • 6
    Nice. And to get the first one: `python -c "import site; print(site.getsitepackages()[0])"` – Brent Faust May 04 '18 at 18:25
  • 4
    This should be in any basic tutorial on using python. I've been pythoning for years and didn't know about the site module. Would've saved so many headaches... – salotz Oct 18 '19 at 16:30
  • 1
    I have suggested a change to Python's official tutorial. Please see [PR #16974](https://github.com/python/cpython/pull/16974) for details, and thanks for the suggestion @salotz! – Peterino Nov 06 '19 at 14:27
  • 2
    I think https://stackoverflow.com/a/52638888/1365918 is easily the best answer to this question. – kapad Feb 11 '20 at 10:06
  • Thanks Peterino, command `python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'` saved me some hours for debuging package when compile tensorflow with bazel. – PhatHV Oct 18 '20 at 11:04
  • `sysconfig.get_path("purelib")` – Bharel May 20 '22 at 16:09
  • 1
    virtualenvs was rewritten after v20.0.0b1, now `site.getsitepackages` is available. see https://github.com/pypa/virtualenv/issues/2378 – YouJiacheng Jul 18 '22 at 16:48
  • I wasn't using virutalenv, and upon investigation the root cause I found is : my default python version is 3.8, but Gunicorn decided to default to use 3.9 – momo668 Mar 23 '23 at 04:29
  • One can also use `python -c "import site; print(site.USER_SITE)"` to get the same output as `python -m site --user-site`. – Stefan Apr 17 '23 at 15:41
699
>>> 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])

MERose
  • 4,048
  • 7
  • 53
  • 79
eudoxos
  • 18,545
  • 10
  • 61
  • 110
378

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)

Greg Dubicki
  • 5,983
  • 3
  • 55
  • 68
Daryl Spitzer
  • 143,156
  • 76
  • 154
  • 173
  • 2
    Does virtualenv provide a way to find its site-packages? – Daryl Spitzer Nov 13 '11 at 14:57
  • 10
    You can use virtualenvwrapper, which has the command `cdsitepackages`, to directly change into the environment's site-packages directory. – john2x Feb 10 '12 at 10:06
  • 6
    @PiotrDobrogost: works for me on Python 2.7 in a virtualenv on Linux – RichVel Mar 06 '13 at 09:57
  • 2
    First comment does not apply anymore: this showed the correct location both outside and inside a virtualenv. – astrojuanlu Apr 15 '16 at 10:21
  • @njwilson Thanks for the solution. Really helped. in windows system, it normally stays in Python Path\Lib\site-packages – Doogle Dec 27 '16 at 02:12
  • 3
    Did not work for me on Windows 10 using Linux bash, it returns `/usr/lib/python3/dist-packages` instead of `/usr/lib/python3.5/dist-packages`. – Delgan Sep 15 '17 at 08:57
  • @Delgan, I imagine that `/usr/lib/python3` is a symlink to `/usr/lib/python3.5`.On my Cygwin,I get the following: `which python3` gives `/usr/bin/python3`, but I find out _that_ is a symlink in several ways.`readlink -f /usr/bin/python3` => `/usr/bin/python3.6m.exe`. `stat /usr/bin/python3` gives output beginning with `File: /usr/bin/python3 -> python3.6m.exe` and has `symbolic link` in the output. `ls -lah /usr/bin/python3` has as its last column `/usr/bin/python3 -> python3.6m.exe`.Those are executables and not library directories. My lib dirs don't have symlinks, but Cygwin != "Linux bash". – bballdave025 Nov 13 '21 at 02:09
  • 2
    The answer has become outdated - distutils is now [deprecated](https://peps.python.org/pep-0632/). – wim Apr 16 '22 at 16:46
109

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.

David Hollander
  • 1,199
  • 1
  • 7
  • 3
  • 3
    If the asker is after a particular package's location, `module.__file__` is the better way. If they're trying to install things… just use the tools. – Tobu Nov 30 '12 at 15:37
  • 2
    `'/usr/lib/pythonX.X/dist-packages' in site.getsitepackages()` on Ubuntu (though it goes *after* `/usr/local/...` in the list). You only get something into `/usr/local` via `sudo pip` and you shouldn't use `sudo pip` on Ubuntu unless you decided to make your own distribution: if you use `sudo pip`, it is your responsibility to make sure that all dependencies of the current and *future* python modules installed via `sudo apt` or `sudo pip` are compatible. Consider [what problem `virtualenv` was created to solve](https://virtualenv.pypa.io/en/stable/#introduction) – jfs Sep 13 '17 at 14:54
  • `python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"`, I get `ModuleNotFoundError: No module named 'requests_unixsocket'` – Timo Sep 14 '21 at 19:25
83

This is what worked for me:

python -m site --user-site
sth
  • 222,467
  • 53
  • 283
  • 367
Ramashri
  • 895
  • 6
  • 2
  • 20
    For me this points to a folder that doesn't even exist (`~/.local/lib/python2.7/site-packages`). – Neil Traft Jul 11 '14 at 18:45
  • 2
    same, in OS X Mavericks , my home .local isn't what I wanted it to find plus yeah its not really there anyways. – radtek Aug 11 '14 at 19:54
  • Its in my main /Library folder I had to manually navigate to it, for some reason the direct full path wasn't working – ericjam Sep 18 '15 at 15:39
  • how do i use the packages installed here? if i do `virtualenv` it complains that the package does not exist. how do i invoke the packages installed at a custom location? – AbtPst Apr 25 '16 at 21:45
  • for me this answer works neither on osx inside or outside virtualenv nor on ubuntu without virtualenv. – jitter May 18 '16 at 18:32
  • This is useful in specific circumstances. For example, if you're using setuptools, you might invoke develop with something like `python setup.py develop --script-dir ~/bin --install-dir /home/thomp/.local/lib/python2.7/site-packages` – dat Sep 30 '16 at 18:02
  • 3
    This tells you where Python will look for user specific packages. Comments like "doesn't even exist" and "isn't what I wanted it to find" don't make sense in this context. – Honest Abe Mar 31 '17 at 19:10
  • import site; site.getusersitepackages() – JeffCharter Mar 29 '23 at 14:58
66

A modern stdlib way is using sysconfig module, available in version 2.7 and 3.2+. Unlike the current accepted answer, this method still works regardless of whether or not you have a virtual environment active.

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. Additionally, distutils is deprecated in 3.10 and will be unavailable soon.

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). The purelib path is where ordinary Python packages will be installed by tools like pip.

At system level, you'll see something like this:

# Linux
$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"
/usr/local/lib/python3.8/site-packages

# macOS (brew installed python3.8)
$ python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))"
/usr/local/Cellar/python@3.8/3.8.3/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages

# Windows
C:\> py -c "import sysconfig; print(sysconfig.get_path('purelib'))"
C:\Users\wim\AppData\Local\Programs\Python\Python38\Lib\site-packages

With a venv, you'll get something like this

# Linux
/tmp/.venv/lib/python3.8/site-packages

# macOS
/private/tmp/.venv/lib/python3.8/site-packages

# Windows
C:\Users\wim\AppData\Local\Temp\.venv\Lib\site-packages

The function sysconfig.get_paths() returns a dict of all of the relevant installation paths, example on Linux:

>>> import sysconfig
>>> sysconfig.get_paths()
{'stdlib': '/usr/local/lib/python3.8',
 'platstdlib': '/usr/local/lib/python3.8',
 'purelib': '/usr/local/lib/python3.8/site-packages',
 'platlib': '/usr/local/lib/python3.8/site-packages',
 'include': '/usr/local/include/python3.8',
 'platinclude': '/usr/local/include/python3.8',
 'scripts': '/usr/local/bin',
 'data': '/usr/local'}

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

python -m sysconfig

Addendum: What about Debian / Ubuntu?

As some commenters point out, the sysconfig results for Debian systems (and Ubuntu, as a derivative) are not accurate. When a user pip installs a package it will go into dist-packages not site-packages, as per Debian policies on Python packaging.

The root cause of the discrepancy is because Debian patch the distutils install layout, to correctly reflect their changes to the site, but they fail to patch the sysconfig module.

For example, on Ubuntu 20.04.4 LTS (Focal Fossa):

root@cb5e85f17c7f:/# python3 -m sysconfig | grep packages
    platlib = "/usr/lib/python3.8/site-packages"
    purelib = "/usr/lib/python3.8/site-packages"

root@cb5e85f17c7f:/# python3 -m site | grep packages
    '/usr/local/lib/python3.8/dist-packages',
    '/usr/lib/python3/dist-packages',
USER_SITE: '/root/.local/lib/python3.8/site-packages' (doesn't exist)

It looks like the patched Python installation that Debian/Ubuntu are distributing is a bit hacked up, and they will need to figure out a new plan for 3.12+ when distutils is completely unavailable. Probably, they will have to start patching sysconfig as well, since this is what pip will be using for install locations.

wim
  • 338,267
  • 99
  • 616
  • 750
  • 1
    This is a great answer, I am happy the new sysconfig module makes this easier. Is there a way to get the local prefix `platlib`, as e.g. `/usr/local/lib/python3.6/site-packages`? Traditionally, locally-installed things should go in `/usr/local`. – eudoxos Dec 07 '19 at 10:18
  • Easily the best answer to this question! Thank you. The only thing that I found missing was the ordering in which these locations are checked when an import statement is encountered. Also, are any of these locations pre-searched/cached when python is loaded? Knowing that would also be useful IMO. – kapad Feb 11 '20 at 10:05
  • In a venv created with `--system-site-packages` this doesn't list all searched directories - specifically the system site directories that are still searched are not listed here... – T S Oct 27 '21 at 11:06
  • Agree with other comments. This is a fantastic answer to the question and works in all contexts I've tried it in. – Jeff Nyman Nov 28 '21 at 17:48
  • 2
    Unfortunately, this answer has a fatal flaw: the `sysconfig` module does not produce correct paths on Debian/Ubuntu and derivatives, whereas the `distutils.sysconfig` module does. – rdb Jan 05 '22 at 07:53
  • I confirm this provide incorrect paths for me on ubuntu – Alleo Apr 16 '22 at 06:40
  • 1
    @Alleo Added an addendum to the answer after investigating what's going on with this distro. What a can of worms. Here's a long [list of stuff Debian messed up in Python](https://gist.github.com/tiran/2dec9e03c6f901814f6d1e8dad09528e). – wim Apr 16 '22 at 19:30
  • @wim that's where I ended up after investigations. This could be just it - screwed up python distro, however when I tried deadsnakes (independent PPA for ubuntu), sysconfig and site provided a different set of paths, which - surprise - again were not in sys.path. I am not sure I have a solution, but I agree about "a can of worms" experience – Alleo Apr 17 '22 at 03:15
  • 1
    @Alleo See [bug #1940705: _distutils and sysconfig returns unexpected paths_](https://bugs.launchpad.net/ubuntu/+source/python3.10/+bug/1940705) – wim Apr 18 '22 at 20:06
37

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.

CharlesB
  • 86,532
  • 28
  • 194
  • 218
Sumod
  • 3,806
  • 9
  • 50
  • 69
  • >>> import pg >>> print pg.__path__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__path__' – Dannid Mar 04 '13 at 22:09
  • it works, i need to find the sklearn package to add to the PYDEV path, thanks. – berkay Jan 02 '15 at 21:20
  • use `django.__file__` for this rather than `__path__`. and, no, it's not a guarantee that this has anything to do with site-packages, but with things like django, that you've most likely *pip installed*, it will do when you're in a hurry and it can be used for other purposes as well (reading a default config file from the file system for example). – JL Peyret Mar 15 '19 at 23:31
  • Based on this and other answers you can do this in one line from the command line to get the path to your `foo.bar` package: `python -c "import foo.bar as _; print(_.__path__[0])"` – snark Dec 12 '19 at 10:29
29

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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 3
    works reliable with `python2` on osx and ubuntu with and without virtualenv but not with `python3` at all. – jitter May 18 '16 at 18:34
  • 2
    2008 was a while back -- this answer was three months before Python 3.0's release. – Charles Duffy May 18 '16 at 18:37
  • sure, but today my comment might help. correct me if am wrong. furthermore, i did not downvote this answer or any other in regards to `python3`. – jitter May 18 '16 at 18:40
26

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

In Linux, you can go to site-packages folder by:

cd $(python -c "import site; print(site.getsitepackages()[0])")
Sourabh Potnis
  • 1,431
  • 1
  • 17
  • 26
  • Adding OS X's 'cut' command to the end of that will give you the string too: ```pip3 show foo | grep Location | cut -d ' ' -f 2``` – cmaceachern Dec 04 '20 at 15:15
  • `cut` is a GNU coreutil https://www.gnu.org/software/coreutils/manual/html_node/The-cut-command.html – xcvbn Jun 30 '21 at 08:42
  • For Windows, when it _must_ be used, `findstr` instead of `grep` works. So, `python -m pip show numpy | findstr "Location"` gives `Location: c:\users\bballdave025\appdata\local\programs\python\python38\lib\site-packages`. Modules you have installed with `pip` are in `site packages`. You can be pretty sure `site-packages` is the location of `pip` itself - as called with `python -m pip ...`. So, `python -m pip show pip | findstr "Location"` shows the same path to `site-packages` we got from `numpy`. Besides `pip`, you can almost always try `virtualenv` (`venv`) & `setuptools`, for *NIX *or* Win – bballdave025 Nov 13 '21 at 01:39
25

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']
fnatic_shank
  • 572
  • 6
  • 12
  • If I remember correctly, dist-packages is specific to Debian and derivates. – Samuel Jul 21 '17 at 21:11
  • 1
    @SamuelSantana you are correct. dist-packages are specific to debian based systems. In this case I invoked `site.getsitepackages()` from the system installation hence the dist-packages, other installations will show site-packages. – fnatic_shank Mar 23 '18 at 05:31
15

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.

cheater
  • 347
  • 2
  • 8
  • 1
    Thanks, this is pretty useful, on py3 with brackets for print it gets me /usr/local/lib/python3.4/dist-packages I'm trying to work out how to get /usr/lib/python3.4/dist-packages so will have to play further. – Stuart Axon Dec 02 '15 at 05:29
  • 6
    requires external library `easy_install` and does not fail gracefully if unavailable which is inadequate :) – jitter May 18 '16 at 18:36
  • 1
    indeed, this is not perfect, but it worked for me and took a lot of time to figure out, so I put it here in hopes someone else can build upon the time I've spent on it already. – cheater May 25 '16 at 15:05
14

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.

Armin Ronacher
  • 31,998
  • 13
  • 65
  • 69
14

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.

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
  • 1
    I guess that's the reason why `get_python_lib()` when being run from within virtualenv shows *site-packages* of Python used to create virtualenv and not the virtualenv's *site-packages*. – Piotr Dobrogost Nov 12 '11 at 19:04
  • 3
    @Piotr That was probably a bug in distutils.sysconfig. I've just tested it an I get the inner site-packages, as expected. – Tobu Nov 30 '12 at 12:37
  • Also tested with Python 2.7 installed in a virtualenv on Linux, and the distutils.sysconfig method works fine to get the inner Python's site-packages. – RichVel Mar 06 '13 at 09:56
14

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'
Qubei
  • 1,053
  • 1
  • 10
  • 19
Pyramid Newbie
  • 6,865
  • 3
  • 24
  • 28
  • I like your low tech approach. Here is a platform independant version: import os; print(os.path.join(os.path.dirname(os.__file__), 'site-packages')) – DougR Dec 04 '20 at 11:22
  • 1
    my original code is platform-independent too. Windows accepts both forward slashes ('/') and back slashes (`\`) just fine as path separators. It is just more common on Windows to use the back slashes. – Pyramid Newbie Mar 14 '21 at 20:45
14

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']
Kristian Glass
  • 37,325
  • 7
  • 45
  • 73
just_an_old_guy
  • 165
  • 1
  • 2
10
from distutils.sysconfig import get_python_lib
print get_python_lib()
Florian Bösch
  • 27,420
  • 11
  • 48
  • 53
8

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
5

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
Sahil Agarwal
  • 555
  • 3
  • 12
  • 1
    This isn't the site-packages directory, but the directory that the package is installed into. This is also only helpful if you're using iPython and not for being able to programmatically get an install directory. – Daniel Underwood Dec 10 '16 at 23:14
3

For those who are using poetry, you can find your virtual environment path with poetry debug:

$ poetry debug

Poetry
Version: 1.1.4
Python:  3.8.2

Virtualenv
Python:         3.8.2
Implementation: CPython
Path:           /Users/cglacet/.pyenv/versions/3.8.2/envs/my-virtualenv
Valid:          True

System
Platform: darwin
OS:       posix
Python:   /Users/cglacet/.pyenv/versions/3.8.2

Using this information you can list site packages:

ls /Users/cglacet/.pyenv/versions/3.8.2/envs/my-virtualenv/lib/python3.8/site-packages/
cglacet
  • 8,873
  • 4
  • 45
  • 60
3

I made a really simple function that gets the job done

import site


def get_site_packages_dir():
        return [p for p  in site.getsitepackages()
                if p.endswith(("site-packages", "dist-packages"))][0]

get_site_packages_dir()
# '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages'

If you want to retrieve the results using the terminal:

python3 -c "import site;print([p for p in site.getsitepackages() if p.endswith(('site-packages', 'dist-packages')) ][0])"

/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages


Angel
  • 1,959
  • 18
  • 37
  • This doesn't work on eg. Ubuntu, where the site-packages directory is named `dist-packages`... Not at all reliable. – rdb Jan 05 '22 at 07:54
  • @rdb just edited the answer (did not know that it was `dist-packages` on Ubunut, now it includes `dist-packages` – Angel Jan 05 '22 at 09:21
2

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.

2

Something that has not been mentioned which I believe is useful, if you have two versions of Python installed e.g. both 3.8 and 3.5 there might be two folders called site-packages on your machine. In that case you can specify the python version by using the following:

py -3.5 -c "import site; print(site.getsitepackages()[1])
Stamatis Tiniakos
  • 698
  • 1
  • 11
  • 33