Alessandro Ferrari
Alessandro Ferrari

Reputation: 13

Bash script to activate (source) python virtualenv using arguments

I have a python virtualenv folder in my home directory where i have quite a few python virtual environments, i would like to make a script that runs this command:

$ source ~/Envs/env_that_i_specify_with_args/bin/activate.

Using an if else would work but i wanted something that looks in the ~/Envs/ directory so that when i add new envs i don't have to manually edit the script, but i could just use arguments to execute that command in another directory.(Something like $ activateEnv -1, to run that command in the first folder in my ~/Envs/ directory, $ activateEnv -2 to run it in the second, etc.)

Upvotes: 1

Views: 3673

Answers (1)

gelonida
gelonida

Reputation: 5630

You cannot make a bash script doing this. The reason is rather simple. A bash script is executed in a subprocess, the virtualenv would be changed for that subprocess, then the bash script ends, you go back to the parent process and restore exactly the same environment that you had before.

In other words: A child process can never change the environment of a parent process.

What you could do is:

  • use a bash alias
  • use a shell function
  • create a script, but 'call' it with source <script_name>

You could for example add following lines to your ~/.bashrc or to your ~/.bash_aliases (if it is called by ~/.bashrc)

setvenv() {
    source /path/to/your/venv_base_dir/$1/bin.activate
}

If you had for example following venvs

/path/to/your/venv_base_dir/venvone
/path/to/your/venv_base_dir/venvtwo
/path/to/your/venv_base_dir/venvthree

Then you just had to type setvenv venvthree to activate.

You asked about activating the first, second or third venv whot would be the first one? the first in alphabetic order? The first one ordered by creation time? I think using the name of the directory (venvone, venvtwo, venvthree) will probably be more intuitive especially if you give meaningful short name to your venvs.

Upvotes: 4

Related Questions