0

I want to permanently add a path to $PYTHONPATH. According to this SO answer, adding

export PYTHONPATH="${PYTHONPATH}:/my/other/path"

to the .bashrc file should accomplish this on a Mac or GNU/Linux distro. However, on my system, $PYTHONPATH is empty, so after doing the export, if I echo $PYTHONPATH, it returns :/my/other/path - which is not a valid path because of the prefixed :. One way around this is to do

export PYTHONPATH="/my/other/path"

but that would clobber other paths if they do exist on different machines. How can I handle both cases?

Obromios
  • 15,408
  • 15
  • 72
  • 127
  • What shell are you using? – Michael M. Jan 13 '23 at 00:40
  • This is also addressed in some answers there: https://unix.stackexchange.com/questions/26047/how-to-correctly-add-a-path-to-path – mkrieger1 Jan 13 '23 at 00:52
  • 1
    Please tag questions according to the problem you are trying to solve, not according to why you want to solve it. A Python expert has no particular advantage in explaining how to set environment variables in a particular shell; an expert in that shell does. – Karl Knechtel Jan 13 '23 at 01:17
  • Thanks, someone has added bash, and I have added zsh as it works for zsh as well. – Obromios Jan 13 '23 at 03:10

4 Answers4

2

The if -z test will tell you if the variable is empty/unset. If so, don't use a colon, otherwise do use one.

if [ -z ${PYTHONPATH} ];
then
    export PYTHONPATH="/my/other/path"
else
    export PYTHONPATH="${PYTHONPATH}:/my/other/path"
fi
John Gordon
  • 29,573
  • 7
  • 33
  • 58
1
PYTHONPATH=$PYTHONPATH:/my/other/path
PYTHONPATH=${PYTHONPATH#:}

This would remove an initial colon resulting from an initially empty PYTHONPATH

user1934428
  • 19,864
  • 7
  • 42
  • 87
1

In zsh you can use typeset -T to create 'tied' variables that are ideal for manipulating paths. These variables can be set to only add colons as needed, to only add unique elements to the path, and to export the result.

typeset -xUT PYTHONPATH pythonpath 

pythonpath+=/usr/local/lib
print $PYTHONPATH
# ==> /usr/local/lib

pythonpath+=/usr/lib
pythonpath+=/usr/local/lib # duplicate not added
print $PYTHONPATH
# ==> /usr/local/lib:/usr/lib

More info here.

Gairfowl
  • 2,226
  • 6
  • 9
0

You can put this in your .bashrc:

[ -z "${PYTHONPATH-}" ] && export PYTHONPATH="/my/other/path" || export PYTHONPATH="${PYTHONPATH}:/my/other/path"

which is the same as the previous answer.