Edgar Martinez Edgar Martinez - 4 years ago 113
Bash Question

Is it possible to source a vitualenv in a shell script and then have the shell that executes the script run in the new env?

Is it possible to run a shell script that sources my python

virtualenv
and then have the shell be in the new environment?

Here is my shell script

#!/usr/bin/env bash
function createProject() {

if [ -e $1 ]
then
rm -r ./$1
fi

if [ -e env-$1 ]
then
rm -r ./env-$1
fi

virtualenv ./env-$1
django-admin startproject $1
}

createProject $1

source ./env-$1/bin/activate

exit 1


I then run
./script.sh hello-world
.
Basically if I were to run
source ./hello-world/bin/activate
my shell the virualenv would be activated and the shell would then be running in the new environment.
How do I accomplish this?

Answer Source

What you want is possible using shell functions only, as they do not spawn separate processes. The problem with your approach is that the virtualenv is activated in a sub-process that was created to run the shell script.

Instead of having a executable shell script, do like this:

function createProject() {

    if [ -e $1 ]
    then
        rm -r ./$1
    fi

    if [ -e env-$1 ]
    then
        rm -r ./env-$1
    fi

    virtualenv ./env-$1
    django-admin startproject $1

    source ./env-$1/bin/activate
}

Save this as createProject.sh and source this file in .bashrc or .bash_profile

source createProject.sh

This way the virtualenv is activated in the current process.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download