Permanently add a directory to PYTHONPATH?

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

    The add a new path to PYTHONPATH is doing in manually by:

    adding the path to your ~/.bashrc profile, in terminal by:

    vim ~/.bashrc
    

    paste the following to your profile

    export PYTHONPATH="${PYTHONPATH}:/User/johndoe/pythonModule"
    

    then, make sure to source your bashrc profile when ever you run your code in terminal:

    source ~/.bashrc 
    

    Hope this helps.

    0 讨论(0)
  • 2020-11-22 01:33

    For me it worked when I changed the .bash_profile file. Just changing .bashrc file worked only till I restarted the shell.

    For python 2.7 it should look like:

    export PYTHONPATH="$PYTHONPATH:/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python"
    

    at the end of the .bash_profile file.

    0 讨论(0)
  • 2020-11-22 01:35

    I added permanently in Windows Vista, Python 3.5

    System > Control Panel > Advanced system settings > Advanced (tap) Environment Variables > System variables > (if you don't see PYTHONPATH in Variable column) (click) New > Variable name: PYTHONPATH > Variable value:

    Please, write the directory in the Variable value. It is details of Blue Peppers' answer.

    0 讨论(0)
  • 2020-11-22 01:37

    In case anyone is still confused - if you are on a Mac, do the following:

    1. Open up Terminal
    2. Type open .bash_profile
    3. In the text file that pops up, add this line at the end: export PYTHONPATH=$PYTHONPATH:foo/bar
    4. Save the file, restart the Terminal, and you're done
    0 讨论(0)
  • 2020-11-22 01:37

    On linux you can create a symbolic link from your package to a directory of the PYTHONPATH without having to deal with the environment variables. Something like:

    ln -s /your/path /usr/lib/pymodules/python2.7/
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
提交回复
热议问题