简体   繁体   中英

Sourcing/Activating Python VirtualEnv in a Bash Script

I am trying to write a simple script that will help me activate (source) the virtualenv and set some environment variables at the same time. Below is the current version that does not yet have any environment variables.

#!/bin/bash

if [ -z "$BASH_VERSION" ]
then
    exec bash "$0" "$@"
fi

# Your script here
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ./django-env/bin/activate; exec /bin/bash -i"

The trouble with this script is two-fold.

  1. When I run it - seemingly successfully as it changes the command line prefix to (django-env) - it is missing the My-Computer-Name: in front of it. Obviously, it is an indication of something as I typically have (django-env) My-Computer-Name: as the prefix.

  2. It does not activate the virtualenv properly. Namely, when I check which python , I am notified that the virtualenv Python is used. On the other hand, when I check for which pip or which python3 , the global system's Python is used.

What can I do to fix these things and have the environment be activated?

I suspect the problem with exec /bin/bash -i — the executed bash could run .bash_profile and .bashrc that change the current environment.

Instead of a shell script that executes shells upon shells you better create an alias or a shell function:

django_activate() {
    cd $1
    . ./django-env/bin/activate
}

Put it in .bashrc so it will be available in all shells and run as django_activate $venv_dir ; for example django_activate ~/projects/work .

The following code does what I intended it to do. I run it with source script.sh

#!/bin/bash

if [ -z "$BASH_VERSION" ]
then
    exec bash "$0" "$@"
fi

# Your script here
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ./django-env/bin/activate"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM