Setting PYTHONPATH with bash script and running nosetests

2.7k views Asked by At

I have the following script that sets a clean PYTHONPATH:

#!/bin/bash

# Get the directory the script is in
DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)

$ Walk up to root of branch dir
DIR=$DIR/../../..

PYTHONPATH=$DIR/module1
PYTHONPATH=$PYTHONPATH:$DIR/module2
PYTHONPATH=$PYTHONPATH:$DIR/module3
PYTHONPATH=$PYTHONPATH:$DIR/module4
export PYTHONPATH

This script is supposed to be run in tandem with a nosetest command to allow tests to import all the necessary modules when needed without any issues:

./path/to/script/PythonPath.sh && nosetests <tons of other arguments>

However, when I run the above command, I get an ImportError on one of the modules stating that it does not exist. I have added an echo statement at the end of the script to help debug and the PYTHONPATH is exactly as it should be. I have also tried setting the PYTHONPATH manually and can't seem reproduce the same issue.

1

There are 1 answers

9
Eric Renouf On BEST ANSWER

You cannot set environment variables in bash that way. The script ends up running in its own process, setting the environment there and not reaching back into yours. In this case you could source or . the script to have it affect your current environment:

source ./path/to/script/PythonPath.sh && nosetests <tons of other arguments>

or

. ./path/to/script/PythonPath.sh && nosetests <tons of other arguments>

Also, you have extra quotes that aren't helpful and at least 1 line missing a comment character. Here's a script with those fixes:

#!/bin/bash

# Get the directory the script is in
DIR=$(cd $( dirname ${BASH_SOURCE[0]} ) && pwd)

# Walk up to root of branch dir
DIR=$DIR/../../..

PYTHONPATH=$DIR/module1
PYTHONPATH=$PYTHONPATH:$DIR/module2
PYTHONPATH=$PYTHONPATH:$DIR/module3
PYTHONPATH=$PYTHONPATH:$DIR/module4
export PYTHONPATH

When I source that file I get:

/tmp/scratch$ . PythonPath.sh
/tmp/scratch$ echo $PYTHONPATH
/tmp/scratch/../../../module1:/tmp/scratch/../../../module2:/tmp/scratch/../../../module3:/tmp/scratch/../../../module4