Implement Django shell and shell_plus look-alike for your project using Ipython.

Tired of loading all the modules into your python shell every time you are to debug something? Want to automate this process 😫😫😫

Satheesh Kumar
3 min readApr 1, 2023

If you have used Django, then you might have come across the 2 frequently used commands provided by Django and Django Extension. The shell command opens an Ipython shell and the shell_plus command that opens the same with all the required imports pre-loaded.

These 2 commands also do a few other things in particular with Django and are not in our scope :)

In this, we will look into implementing the same for any python project that we have created.

Requirements

  1. Python3
  2. Ipython

Install Ipython:

pip install ipython

Why Ipython?

The Ipython python package exposes the start_ipython definition that can be used to open an Ipython shell from anywhere. Ipython is a vastly improved Python interpreter. It has syntactic sugar that improves exploration, debugging, and optimisation in a big way.

Opening an Ipython shell

Hope an Ipython shell got spawned. Now, let's assume that the datetime module is most frequently used in our project and we need it to be auto-loaded inside our shell.

Opening an Ipython shell with datetime auto loaded

If you see now we are passing an additional param user_ns to start_ipython. user_ns is a dictionary to initialise the IPython user namespace with particular values.

Now, inside the shell, if you try datetime you will be able to access the module without importing.

Create manage.py like Django

The manage.py is the CLI entry point for a Django project. It exposes multiple commands that can be used to administrate the entire application. Since we want to keep things short we will use click and create a CLI with shell and shell_plus commands.

Install click

pip install click
  1. Create a new manage.py file.
  2. chmod +x manage.py and make it an executable.
  3. Let's write some code to the file.
#!/usr/bin/env python

import click
import datetime

from IPython import start_ipython


@click.group(help="Django Like Shell and Shell Plus")
def cli():
...


@cli.command(help="Django Like Shell")
def shell():
start_ipython(argv=[])


@cli.command(help="Django Like Shell Plus", name="shell_plus")
def shell_plus():
start_ipython(
argv=[],
user_ns={
"datetime": datetime,
},
)


if __name__ == "__main__":
cli.add_command(shell)
cli.add_command(shell_plus)
cli()

Now, our manage.py is ready to use. Try running ./manage.py shell and ./manage.py shell_plus to experience it.

The code used in this article is available at https://github.com/satheesh1997/tut-django-like-shell-plus.

Disclaimer:

This article gives a simple implementation that looks like one in Django. It's upon your creativity to add more features like how it's done in the Django project.

Hope you ❤️ this, See you in the next tutorial 👋.

--

--