Using .pth files

前端 未结 2 474
耶瑟儿~
耶瑟儿~ 2020-12-02 14:03

I am trying to make a module discoverable on a system where I don\'t have write access to the global site-packages directory, and without changing the environme

相关标签:
2条回答
  • 2020-12-02 14:46

    You can make a .pth (path) file in a directory already in sys.path so it can be included/

    0 讨论(0)
  • 2020-12-02 15:10

    As described in the documentation, PTH files are only processed if they are in the site-packages directory. (More precisely, they are processed if they are in a "site directory", but "site directory" itself is a setting global to the Python installation and does not depend on the current directory or the directory where the script resides.)

    If the directory containing your script is on sys.path, you could create a sitecustomize.py in that directory. This will be loaded when Python starts up. Inside sitecustomize.py, you can do:

    import site
    site.addsitedir('/some/dir/you/want/on/the/path')
    

    This will not only add that directory, but will add it as a "site directory", causing PTH files there to be processed. This is handy if you want to create your own personal site-packages-like-directory.

    If you only need to add one or two directories to the path, you could do so more simply. Just create a tiny Python library that manipulates sys.path, and then import that library from your script. Something like:

    # makepath.py
    import sys
    sys.path.append('/whatever/dir/you/want')
    
    # script.py
    import makepath
    

    Edit: Again, according to the documentation, there is the possibility of a site-specific directory in %APPDATA%\Python\PythonXY\site-packages (on Windows). You could try that, if in fact you have write access to that (and not just to your script directory).

    0 讨论(0)
提交回复
热议问题