8

I wrote a shell script as.

    source ve/bin/activate

Saved it as activate_shell.sh latter when I ran the script with command.

    bash activate_shell.sh

The script is being run with no error but the virtual environment is not being activated.

Sar009
  • 2,166
  • 5
  • 29
  • 48
  • If so? `./activate_shell.sh` , before `chmod +x activate_shell.sh` – crazyzubr Dec 05 '13 at 05:14
  • I tried that first but it was giving error command not found – Sar009 Dec 05 '13 at 05:16
  • the "error command not found" probably means that the executable bit wasn't set. run `chmod +x activate_shell.sh` to set that – Thayne Dec 05 '13 at 05:18
  • Maybe error in the script? – crazyzubr Dec 05 '13 at 05:21
  • I did tried that but result was that the script executed without error but virtual environment was not activated. I also tried sh activate_shell.sh error was source: not found – Sar009 Dec 05 '13 at 05:27
  • Got the answer http://stackoverflow.com/a/13122317/992665 thanks for flagging the question anyway. – Sar009 Dec 05 '13 at 05:51
  • Shell is not bash, so it's not strictly a duplicate. Source doesnt exists in shell. so accepted answer is not actually useful. I would say either repoen or tagging with bash. – The Fool Mar 31 '22 at 20:08

2 Answers2

14

Your activation script path, ve/bin/activate, is relative. The script will only work from one directory. But the problem is not here.

What does bin/activate do? It modifies the shell in which it runs. This is why you have to source it and not invoke as a regular program.

The script you wrote starts its own copy of shell (bash), activates the virtual environment inside it, and exits, destroying the just-activated environment. If your script invoked Python after sourcing the bin/activate, it would be the Python from the virtual environment, not the system one.

If you want a simple, easy-to-type command to activate a virtualenv, define a shell function:

ve() { source $1/bin/activate; }

(Yes, type the above line right into your shell prompt.)

Then type ve foo and virtualenv named foo will be activated in your current shell, provided that you're in the right directory.

Should you need to cope with a massive amount of virtualenvs, take a look at virtualenvwrapper.

AndyG
  • 39,700
  • 8
  • 109
  • 143
9000
  • 39,899
  • 9
  • 66
  • 104
5

Using a script to run source command defeats its purpose as bash activate_shell.sh will create another shell. All modification by the active command would modify the newly created shell, which terminate upon completion of your activate_shell.sh script.

A easy way to do this is to add alias to your .bash_profile instead:

alias activate_shell="source ve/bin/activate"
marcoseu
  • 3,892
  • 2
  • 16
  • 35