Skip to content

Instantly share code, notes, and snippets.

@necaris
Created February 7, 2012 13:53
Show Gist options
  • Save necaris/1759781 to your computer and use it in GitHub Desktop.
Save necaris/1759781 to your computer and use it in GitHub Desktop.
IPython config snippet that makes it work with virtualenv
# Configuration snippet to let system-wide IPython work with virtualenvs
# Code taken from Ahmed Soliman's post at:
# (http://www.ahmedsoliman.com/2011/09/27/use-virtualenv-with-ipython-0-11/)
# Tweaked by Rami Chowdhury
from os import environ
from os.path import join, sep
from sys import version_info
if version_info[0] > 2:
# Python 3.x doesn't define this, so for convenience, we do.
def execfile(fname, global_vars):
with open(fname) as fh:
exec(compile(fh.read(), fname, "exec"), global_vars)
if 'VIRTUAL_ENV' in environ:
# OK, we're running in a virtualenv - run virtualenv's own activation
# script to set it up just as if we were using the environment's Python
virtual_env_dir = environ['VIRTUAL_ENV']
activate_this = join(virtual_env_dir, "bin", "activate_this.py")
execfile(activate_this, dict(__file__=activate_this))
# At this point everything should be set up, so just print an informative
# message, and optionally change the IPython prompt, and we're done
virtual_env_name = virtual_env_dir.split(sep)[-1]
message = '[using virtualenv "{0}" ({1})]'.format(virtual_env_name,
virtual_env_dir)
print(message)
# If you don't want to change your IPython prompt to match your virtualenv
# (the way your shell prompt changes), then comment this bit out.
conf = get_config()
conf.PromptManager.in_template = virtual_env_name + " [\\#]: "
del virtual_env_dir
del environ, join, sep, version_info
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment