pep 370

Damjan Georgievski edited this page Oct 28, 2018 · 2 revisions

pep-370 based virtual environments

I don't like virtualenv! It seems to me like a huge hack. Python versions more recent than 2.6 have support that can almost fully replace virtualenv without the hacks and ugliness.

This is a bash helper function that will ease the creation of virtual environments acording to the ##pep-370## standard.

The activate script is loosely based on virtualenv, but overall this is much simpler tool than virtualenv since it doesn't need to make a copy (or a link) of the python binary or of anything from ##/usr/lib/python2.6/##.

# Create a PEP-370 Python virtual env
function create_env () {
    ENV=`readlink -f $1` || return 1
    mkdir $ENV || return 1
    mkdir $ENV/bin || return 1
    cat <<-EOF > $ENV/bin/activate
        # first check if other env is active
        [ x"$PYTHONUSERBASE" != x ] && echo "PYTHONUSERBASE already active from $PYTHONUSERBASE. Use 'deactivate' first." && return 1

	# setup pep-370
        # alternatively ENV=$(dirname $(readlink -f $BASH_SOURCE)/..) would make the activate script stateless

	# configure pip
	export PIP_INSTALL_OPTION=--user

	# setup the bash prompt

	# setup the bash path

	# .. and at last allow for cleanup
	alias deactivate='PATH=\$_OLD_PATH; PS1=\$_OLD_PS1; unset PIP_INSTALL_OPTION; unset PYTHONUSERBASE; unalias deactivate'
    echo "source $ENV/bin/activate in your shell to activate this environment."
# end of PEP-370 creator

I have this in my ##/.bashrc##, but on Debian/Ubuntu you can put it in ##/.bash_aliases## too. It seems to work in zsh too. But beware of the TAB characters - they are needed in that cat <<-EOF segment.

The activate script also configures pip (versions 0.7 and up) to install in the virtual environment by default.


damjan$ create_env xxx
damjan$ source xxx/bin/activate
[xxx]damjan$ pip install Flask
[xxx]damjan$ python
>>> import sys
>>> sys.path
[xxx]damjan$ deactivate
damjan$ ls xxx/lib/python2.6/site-packages/ # too see how simple and elegant it is


  • error handling and reporting
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.