Permanently add a directory to PYTHONPATH?

前端 未结 19 1323
别那么骄傲
别那么骄傲 2020-11-22 01:12

Whenever I use sys.path.append, the new directory will be added. However, once I close python, the list will revert to the previous (default?) values. How do I

19条回答
  •  悲哀的现实
    2020-11-22 01:29

    To give a bit more explanation, Python will automatically construct its search paths (as mentioned above and here) using the site.py script (typically located in sys.prefix + lib/python/site-packages as well as lib/site-python). One can obtain the value of sys.prefix:

    python -c 'import sys; print(sys.prefix)'
    

    The site.py script then adds a number of directories, dependent upon the platform, such as /usr/{lib,share}/python/dist-packages, /usr/local/lib/python/dist-packages to the search path and also searches these paths for .pth config files which contain specific additional search paths. For example easy-install maintains its collection of installed packages which are added to a system specific file e.g on Ubuntu it's /usr/local/lib/python2.7/dist-packages/easy-install.pth. On a typical system there are a bunch of these .pth files around which can explain some unexpected paths in sys.path:

    python -c 'import sys; print(sys.path)'
    

    So one can create a .pth file and put in any of these directories (including the sitedir as mentioned above). This seems to be the way most packages get added to the sys.path as opposed to using the PYTHONPATH.

    Note: On OSX there's a special additional search path added by site.py for 'framework builds' (but seems to work for normal command line use of python): /Library/Python//site-packages (e.g. for Python2.7: /Library/Python/2.7/site-packages/) which is where 3rd party packages are supposed to be installed (see the README in that dir). So one can add a path configuration file in there containing additional search paths e.g. create a file called /Library/Python/2.7/site-packages/pip-usr-local.pth which contains /usr/local/lib/python2.7/site-packages/ and then the system python will add that search path.

提交回复
热议问题