Permanently add a directory to PYTHONPATH?

前端 未结 19 1337
别那么骄傲
别那么骄傲 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:38

    Instead of manipulating PYTHONPATH you can also create a path configuration file. First find out in which directory Python searches for this information:

    python -m site --user-site
    

    For some reason this doesn't seem to work in Python 2.7. There you can use:

    python -c 'import site; site._script()' --user-site
    

    Then create a .pth file in that directory containing the path you want to add (create the directory if it doesn't exist).

    For example:

    # find directory
    SITEDIR=$(python -m site --user-site)
    
    # create if it doesn't exist
    mkdir -p "$SITEDIR"
    
    # create new .pth file with our path
    echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth"
    

提交回复
热议问题