Running a python script within a shell script - how to activate the obspy Anaconda environment

Dear all,

I have obspy installed in my Mac OS X 10.11.6 (El Capitan), using Anaconda, and creating and environment with python3.5 called “obspy”, as suggested in https://github.com/obspy/obspy/wiki/Installation-via-Anaconda

I like this approach and it works very well (although I don’t always remember to type “source activate obspy” before running my scripts).

However I have found a difficulty when I call a python script that needs obspy from within a bash shell script. Instead of running the “obspy” environment, the python script uses the default python3 environment. I have tried including “source activate obspy” in the shell script but that does not help.

The solution I found is replacing the usual initial she-bang in the python script:

#!/usr/bin/env python3

with:

#!/Users/antonio/anaconda/envs/obspy/bin/python

However I find this not very elegant, nor portable. Does anybody know of a better way of doing this?

Many thanks!
Antonio

Antonio Villaseñor
Institute of Earth Sciences Jaume Almera (ICTJA-CSIC)
c/ Lluís Solé i Sabarís s/n
08028 Barcelona, Spain

ph: +34 93 409 5410
e-mail: antonio.villasenor@csic.es
http://orcid.org/0000-0001-8592-4832

Hi Antonio,

calling `source activate obspy` before you run the shell script should
work. Then just use `python script.py` in the bash script.

This is IMHO also the most portable solution as people might want to run
it with different environments so it should not be hard-coded in the
bash script.

If that is no acceptable to you for some reason you can also directly
use the python binary in the obspy environment in the bash script:

/path/to/conda/installation/envs/obspy/bin/python script.py

Cheers!

Lion

Dear Lion,

Thanks for the suggestion, it does work and it is indeed more portable than my quick fix!

However, while testing your solution I found that my problem was caused by something else: my shell script is a C-shell script, not bash. Therefore, the environment defined when you do “source activate obspy” in bash, is not passed to the C-shell script.

So, the good news is that python scripts that use obspy can be called without problems from a bash shell script (provided that you entered “source activate obspy” in your bash shell before).

In my case the best option is to re-write the C-shell script in bash.

Thanks again!!
Antonio

Hi Antonio,

rewriting csh to bash is in most cases a good idea in my opinion.

Alternatively you could probably also launch the script from within a
csh shell in which case I guess it would inherit the activated
environment? This script collection can activate/deactivate conda
environments in C shell:

https://gist.github.com/mikecharles/f09486e884a0b41e1e8f

Cheers!

Lion

Dear Lion,