2

I am returning strings from a python module, for consumption within a bash script.

This is what I have so far:

SCRIPT_DIR=/somepath/to/scripts/folder
cd $SCRIPT_DIR/eod

python_cmd='import sys;
            sys.path.append("/somepath/to/scripts/folder/utils"); 
            import settings as st; 
            print " ".join(st.foo())'

# Fix indentation for Python
python_cmd=${python_cmd//'            '/''}

my_array=(`python -c "$python_cmd"`)

I want to use the DRY philosophy in the snippet above. However, the string/somepath/to/scripts/folder is repeated in the script. I would like to pass the definition of $SCRIPT_DIR into the python_cmd - however I tried (replacing the path string in python_cmd with $SCRIPT_DIR/utils and it failed with the following error:

Traceback (most recent call last):
  File "<string>", line 3, in <module>
ImportError: No module named settings

What am I doing wrong?

Note:

I am running bash 4.1.5

2 Answers 2

3

Don't bother to pass the string in at all. Instead of modifying sys.path in the Python text, modify the PYTHONPATH environment variable in the bash script. It's easier, and is the preferred way to affect the import path anyway.

An example of how to set the path:

SCRIPT_DIR=/somepath/to/scripts/folder
cd $SCRIPT_DIR/eod

export PYTHONPATH=$SCRIPT_DIR
python_cmd='import settings as st; 
            print " ".join(st.foo())'

I also have to say, this seems like an odd way to glue components together, but I don't have enough information to recommend a better way.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry to be a pain. but could you post a few lines to show how I can use PYTHONPATH instead? - thanks.
2

Because the python command is enclosed in single quotes, $SCRIPT_DIR is not expanded. Try this:

python_cmd='import sys;
            sys.path.append("'$SCRIPT_DIR'");
            import settings as st; 
            print " ".join(st.foo())'

That said, I would go with the answer that modifies PYTHONPATH.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.