How do source from a user's python environment and perform a pip install

Viewed 35

How do I install Python modules as another user into that user's python environment?

I tried the following lines in a bash script but pip install is still running in the global python environment.

sudo -i -u otheruser source /home/otheruser/project/project-env/bin/activate
sudo -i -u otheruser pip install -r /home/otheruser/project/project/requirements.txt

Thanks.

1 Answers
sudo -i -u otheruser source

runs in a new shell. When the command finishes the shell exits and all changes brought by sources disappears. You have to run all commands in one shell:

sudo -i -u otheruser bash -c "
    source /home/otheruser/project/project-env/bin/activate
    pip install -r /home/otheruser/project/project/requirements.txt
"

You can do this simpler. To run a Python script in a virtual environment you don't need to source its activation script. Just run python from the virtual environment:

sudo -i -u otheruser /home/otheruser/project/project-env/bin/python -m pip install -r /home/otheruser/project/project/requirements.txt
Related