Brenton Horne Brenton Horne - 9 days ago 7
Bash Question

How does one enter a Python virtual environment and run shell commands in it from a shell script?

I have been writing a shell script to be run in a CentOS 7 Docker container in order to create an AppImage. In this script I would like to run the Shell command

pip install -U spyder
from within a Python virtual environment (started by running
source AppDir/usr/bin/activate
) started by the shell script. The problem is that I don't know how to do this because lines in the script after the
source AppDir/usr/bin/activate
line are ignored (as at this point in the script, the shell has entered the Python virtual environment). So is there some option I need to pass the
source AppDir/usr/bin/activate
command so that it will run the
pip install -U spyder
command in this Python virtual environment?

Answer

You can install your requirement without activating virtual environment, but with providing full path to your virtualenv pip.

<path_to_virtualenv>/bin/pip install -U spyder

Because what activate is doing it's putting your virtualenv bin/ folder before the PATH, so that pip, python commands would be references to your viartualenv's before global ones. From source of activate:

VIRTUAL_ENV="<path_to_env>"
export VIRTUAL_ENV

_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH