I've written a python program. And if I have a shebang like this one:
#!/usr/bin/python
and I make the file executable with:
$ chmod 755 program.py
I can run the program like so:
$ ./program.py
Here is the issue. I use the conda virtual environments. When I run the program like above, the system creates a subshell that does not recognize the active environment:
(my_env) $ ./program.py
ImportError: No module named pymongo
If I do it this way, however...
(my_env) $ python program.py
# blah blah... runs great
How do I specify the right environment for use in the subshell? Is it possible? I'd like to save my fingers the effort of typing the six character string that is python
.
Another post, Shebangs in conda managed environments, briefly touches on this but does not provide the right answer. Instead of activating the environment in the subshell, it just says, go ahead and ignore the shebang... just use the $ python program.py
syntax.
conda run
If you always plan to run the script from a shell session where
conda
is defined, then another alternative is let Conda load the env using theconda run
command. In this case, the shebang would beThe advantage here is that you don't need the env to be activated when you call
./program.py
and you don't have to hardcode the location of the interpreter.Note: This command was added as a "preview" in Conda v4.6.0 (see Release Notes) to address the issue of running a command inside an env.
In your script, change...
...to:
The python used by an activated conda environment is
${CONDA_PREFIX}/bin/python
and not/usr/bin/python
Notice the difference?
You can also point directly to the environment with the shebang line so you need not depend on something setting up the parent environment prior to calling the script.
First determine your preferred python environment's path:
Then use it in a script:
The above script would give output like this:
Having a non-generic command in the shebang makes the script less portable, but if you depend the specific packages in a particular virtual environment, this is what you want.