Posts tagged ‘python2’

Make IPython recognise virtualenv

IPython doesn’t currently recognise when you’re in a virtualenv. (See high priority issue).

There are currently 3 popular workarounds for those without root access.

Workaround #1. Add the following to ~/.bashrc or ~/.zshrc:

alias ipython="python /usr/bin/ipython"

Workaround #2. Install a local virtualenv copy of ipython:

$ pip install ipython

Workaround #3. Create ~/.config/ipython/profile_default/ipython_virtualenv.py with the following (for Python3):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Modified for Python 3 (https://gist.github.com/1759781)
from os import environ
from os.path import join, sep
 
if 'VIRTUAL_ENV' in environ:
    virtual_env_dir = environ['VIRTUAL_ENV']
    activate_this = join(virtual_env_dir, "bin", "activate_this.py")
    exec(compile(open(activate_this).read(), activate_this, 'exec'),
         dict(__file__=activate_this))
    virtual_env_name = virtual_env_dir.split(sep)[-1]
    message = 'virtualenv "{0}" ({1})]'.format(virtual_env_name,
                                               virtual_env_dir)
    print(message)
    del virtual_env_dir
del environ, join, sep

Add the following to ~/.config/ipython/profile_default/ipython_config.py:

c.InteractiveShellApp.exec_files = ['ipython_virtualenv.py']

From the IPython FAQ, those with root access can access it by modifying the shebang in /usr/bin/ipython

1
#!/usr/bin/env python