views:

3689

answers:

5

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

+18  A: 

From "How to Install Django" documentation (though this is useful to more than just Django installation) - execute the following from the shell:

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"
Daryl Spitzer
could you please format that code a bit better?
Florian Bösch
Its formatted like this to make it a one-liner to be run from the command-prompt. Just take the code in double quotes and replace the ; with a newline to get the more typical python script formatting
Brendan
A: 
from distutils.sysconfig import get_python_lib
print get_python_lib()
Florian Bösch
+1  A: 

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
+1  A: 

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
+1  A: 

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.

Zoran