Bash script to source a Python virtual environment

When loading a python virtual environment I need to run:

source venv/bin/activate

I want an alias for this command because I have to run it all the time. So I put the following in a file called "load.sh":

#!/bin/bash
source venv/bin/activate

And ran

chmod +x load.sh

However, now when I run ./load.sh there is no effect. My suspicion is that the word "source" may be the issue. But I don't know. Any ideas? Thanks.

2 Answers

The source venv/bin/activate commands modifies load.sh's environment. When load.sh ends, this environment is forgotten. Also, it will only work if you're in the $HOME directory.

I think what you really want is to add to your ~/.bashrc:

alias venv="source $HOME/venv/bin/activate"

then

venv

will do the trick.

0

Another alternative is using virtualenvwrapper.

You can install it using pip install virtualenvwrapper (use pip3 for Python3).
After that, add the following lines to the end the .bashrc file:

export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source ~/.local/bin/virtualenvwrapper.sh
export WORKON_HOME=~/.virtualenvs
export PIP_VIRTUALENV_BASE=~/.virtualenvs
export PIP3_VIRTUALENV_BASE=~/.virtualenvs

Save and exit then you have to reload .bashrc by running source ~/.bashrc (just for once).
After that, whenever you want to create an env, run mkvirtualenv <your_env_name>.
And if you want to work on an env or to switch between envs, run workon <env_name>.
If you want to deactivate an env, run deactivate.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like