1

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.)

  • Any thoughts on how to do this?
  • Please explain it in a rather simple manner as i am fairly new to Linux.
1
  • Learn to use virtualenvwrapper, it's really wonderful! Commented Nov 15, 2019 at 1:13

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the fast response, this worked flawlessly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.