Search code examples
bashenvironment-variablesgit-bashsys

add multiple directory-paths to $PYTHONPATH (Git-Bash in Windows)


I want to add multiple paths (A,B) to the PYTHONPATH environment variable in Windows every time I launch a Git Bash. Python should draw it's dependencies from path A and B in addition to the dependencies that already exist:

#output
$ python -c "import sys; print(sys.path)"
[**'C: \\ProgramData\\A', 'C: \\ProgramData\\B'**, 'C:\\Program Files\\Python312\\python312.zip', ...]

There are solutions to this problem for a purely Linux based system, where quotationmarks are not needed ('"') and for Windows via GUI>settings>path-vairables. The latter is not an option here (admin rights etc.).


I tried to manipulate the PYTHONPATH variable in ~./bash_profile in two manners:

  1. Append Path B to A via ":" : This yields both paths in a shared string
#~/.bash_profile
export PYTHONPATH="/ProgramData/A"
export PYTHONPATH=$PYTHONPATH:"/ProgramData/B"
alias python='winpty python'
- - - - - - - - - - - - - -
#output
$ python -c "import sys; print(sys.path)"
['', 'C:\\ProgramData\\A:\\ProgramData\\B', 'C:\\Program Files\\Python312\\python312.zip',...]

  1. Append Path B in the same manner as A : Only the last exported path will be considered
#~/.bash_profile
export PYTHONPATH="/ProgramData/A"
export PYTHONPATH="/ProgramData/B"
alias python='winpty python'
- - - - - - - - - - - - - -
#output
$ python -c "import sys; print(sys.path)"
['', 'C:\\ProgramData\\B', 'C:\\Program Files\\Python312\\python312.zip',...]


How do I need to modify the export statements in order to obtain separate entries in sys.path?


Solution

  •    export PYTHONPATH=$PYTHONPATH:"/ProgramData/B"
    

    How do I need to modify the export statements in order to obtain separate entries in sys.path?

    For every other OS you would have it right already. But windows is quirky, and since it has the concept of "Drives" it can't use : as the path element delineator. Instead windows must use ; as the path seperator.

    export PYTHONPATH="/ProgramData/A"
    export PYTHONPATH="$PYTHONPATH;/ProgramData/B"
    

    Better to append your settings to the existing PYTHONPATH instead of truncating it:

    export PYTHONPATH="C:/ProgramData/A;C:/ProgramData/B;$PYTHONPATH"