So you love the Django shell? The interactive prompt that has your Django stuff loaded and ready for some quick prototyping? You always wanted to embed something similar in your Python apps too? Well, it’s painlessly simple with the “code” module. It offers us the “InteractiveConsole” class which we can extend to quickly get a REPL which is basically the Python REPL with our customizations. The code is heavily documented. Going through it should be adequate to understand whats going on:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
from code import InteractiveConsole # Our own console implementation # Subclasses object since we want to use new style classes class MySuperCoolConsole(InteractiveConsole, object): # Redefine interact method to add our own banners # Subclassing was necessary, we could pass it to # a new InteractiveConsole instance directly def interact(self): banner = "=====" * 3 + "\n" + "SUPER COOL CONSOLE" + "\n" + "VERSION: 0.1" + "\n" + "=====" * 3 super(MySuperCoolConsole, self).interact(banner) # Customize the prompt def raw_input(self, prompt=""): prompt = "[=>] " return raw_input(prompt) # We want to inject some preset variables ("names" in Python) # Grab the locals(), add our own to it local_names = locals() local_names['name'] = 'masnun' local_names['email'] = 'masnun@transcendio.net' # Pass the modified locals, call interact to launch REPL console = MySuperCoolConsole(locals=local_names) console.interact() |
What did we do? We subclassed InteractiveConsole to create our own implementation. And then ran it 🙂
Test run outputs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
~/Codes/py ⮀ python test.py =============== SUPER COOL CONSOLE VERSION: 0.1 =============== [=>] email 'masnun@transcendio.net' [=>] name 'masnun' [=>] print 'those were injected' those were injected [=>] print 'nice, no?' nice, no? [=>] 2 + 3 5 [=>] ^D ~/Codes/py ⮀ |