Sunday, September 11, 2016

Imports and sys.path

Python finds imported packages by looking at the directories listed in the sys.path.

To check the sys.path:

[ed@localhost ~]$ python -m site
sys.path = [
    '/home/ed',
    '/usr/lib/python27.zip',
    '/usr/lib64/python2.7',
    '/usr/lib64/python2.7/plat-linux2',
    '/usr/lib64/python2.7/lib-tk',
    '/usr/lib64/python2.7/lib-old',
    '/usr/lib64/python2.7/lib-dynload',
    '/usr/lib64/python2.7/site-packages',
    '/usr/lib64/python2.7/site-packages/gtk-2.0',
    '/usr/lib/python2.7/site-packages',
    '/usr/lib/python2.7/site-packages/setuptools-26.1.1-py2.7.egg',
]
USER_BASE: '/home/ed/.local' (exists)
USER_SITE: '/home/ed/.local/lib/python2.7/site-packages' (doesn't exist)
ENABLE_USER_SITE: True

Or, from within python:

[ed@localhost ~]$ python
Python 2.7.12 (default, Sep  2 2016, 14:46:00)
[GCC 6.1.1 20160621 (Red Hat 6.1.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys, pprint
>>> pprint.pprint(sys.path)
['',
 '/usr/lib/python27.zip',
 '/usr/lib64/python2.7',
 '/usr/lib64/python2.7/plat-linux2',
 '/usr/lib64/python2.7/lib-tk',
 '/usr/lib64/python2.7/lib-old',
 '/usr/lib64/python2.7/lib-dynload',
 '/usr/lib64/python2.7/site-packages',
 '/usr/lib64/python2.7/site-packages/gtk-2.0',
 '/usr/lib/python2.7/site-packages',
 '/usr/lib/python2.7/site-packages/setuptools-26.1.1-py2.7.egg']

How python builds the sys.path is surprisingly complicated. A brief description can be found on Lee on Coding blog post. A more detailed description can be found in this Stackoverflow answer. Also take a look at the python sys.path docs.

The sys.path is put together at load-time by the automatically imported python site module.

The site module evaluates any .pth files it can find




No comments:

Post a Comment