using profiles in ipython and Django

Last updated on by michaelyin

Intro

When I write my code in django shell, I found that django can launch ipython by typing ././manage.py shell if ipython has been installed in virtualenv. However, I it seems it can not pass some argument like --profile into the ipython. So I can not let the ipython run some startup files by default.

I did some research on google, statckoverflow and so on, but failed to found a good solution to fix this problem. So I wrote this post to help some guy who faced the same problem.

Solution 1.

Some people set an environment variable called PYTHONSTARTUP or use python file called pythonrc to make python shell to run some code evertytime you open shell.

This solution can work in some cases, but I want the shell to auto run the code in ipython startup dir, so I move on to find a solution.

Solution 2.

I found a python package called django-extensions which is a collection of custom extensions for the Django Framework. I checked the command shell_plus and found that it can pass argument to ipython notebook, so I dive into the source code and found a way.

Setp 1

Install the django-extensions by typing pip install django-extensions

Setp 2

open file $VIRTUALENV/lib/python2.7/site-packages/django_extensions/management/commands/shell_plus.py and find the method named get_ipython, it should be look like this

def get_ipython():
    try:
        from IPython import embed

        def run_ipython():
            imported_objects = import_objects(options, self.style)
            embed(user_ns=imported_objects)
        return run_ipython
    except ImportError:
        str_exc = traceback.format_exc()
        # IPython < 0.11
        # Explicitly pass an empty list as arguments, because otherwise
        # IPython would use sys.argv from this script.
        # Notebook not supported for IPython < 0.11.
        try:
            from IPython.Shell import IPShell
        except ImportError:
            return str_exc + "\n" + traceback.format_exc()

        def run_ipython():
            imported_objects = import_objects(options, self.style)
            shell = IPShell(argv=[], user_ns=imported_objects)
            shell.mainloop()
        return run_ipython

shell_plus use embed to launch ipython, I found in ipython doc you want to load full IPython configuration, you probably want IPython.start_ipython() instead. So I just replace it.

Here we go:

def get_ipython():
    try:
        from IPython import start_ipython
        ipython_arguments = getattr(settings, 'IPYTHON_ARGUMENTS', [])
        def run_ipython():
            imported_objects = import_objects(options, self.style)
            start_ipython(ipython_arguments, user_ns=imported_objects)
        return run_ipython
    except ImportError:
        str_exc = traceback.format_exc()
        # IPython < 0.11
        # Explicitly pass an empty list as arguments, because otherwise
        # IPython would use sys.argv from this script.
        # Notebook not supported for IPython < 0.11.
        try:
            from IPython.Shell import IPShell
        except ImportError:
            return str_exc + "\n" + traceback.format_exc()

        def run_ipython():
            imported_objects = import_objects(options, self.style)
            shell = IPShell(argv=[], user_ns=imported_objects)
            shell.mainloop()
        return run_ipython
Setp 3

Add some setting to settings.py of django

IPYTHON_ARGUMENTS = [
    '--profile=econometrics',
]
Setp 4

run ./manage.py shell_plus, you can see IPython profile: econometrics in the output.

# Shell Plus Django Imports
from django.utils import timezone
from django.conf import settings
from django.core.cache import cache
from django.db.models import Avg, Count, F, Max, Min, Sum, Q
from django.core.urlresolvers import reverse
from django.db import transaction

Python 2.7.8 (default, Oct 19 2014, 16:03:53)
Type "copyright", "credits" or "license" for more information.

IPython 2.3.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

IPython profile: econometrics

In [1]:

Ref

http://ipython.org/ipython-doc/2/api/generated/IPython.terminal.embed.html

http://dlo.me/archives/2014/09/08/pythonrc/

Send Me Message

Tell me more about your project and see if I can help you.

Contact Me