This feels like a bit of a face-plant moment but I've never understood why anyone would use the code module when you can use the pdb when the pdb is like the code module but with less.
What you use it for is to create you own custom shell. Django does this nicely with it's shell management command. I often find myself doing this:
$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from this import that
>>> from module import something
>>> from db import connection
>>> con = connection('0.0.0.0', bla=True)
>>> con.insert(something(that))
And there's certain things I almost always import (depending on the project). So use code
to write your own little custom shell loader that imports all the stuff you need. Here's one I wrote real quick. Ultra useful time-saver:
#!/usr/bin/env python
import code, re
if __name__ == '__main__':
from apps.main.models import *
from mongokit import Connection
from pymongo.objectid import InvalidId, ObjectId
con = Connection()
db = con.worklog
print "AVAILABLE:"
print '\n'.join(['\t%s'%x for x in locals().keys()
if re.findall('[A-Z]\w+|db|con', x)])
print "Database available as 'db'"
code.interact(local=locals())
This is working really well for me and saving me lots of time. Hopefully someone else finds it useful.
Comments
Post your own commentI think you mean, "why anyone would use the pdb module when you can use the code module" ?
No I did not mean that.
What I was trying to say was that I thought (note: past tense) that pdb was like code but better. Now I know (note: present tense) that code can be used for other cool stuff.
That is very cool, and I also didn't know you could use the code module that way. In this specific case could you have used sitecustomize.py? I've often dealt with the "must set up all this state" thing in the python command window by adding things to a project specific sitecustomize.py file, or using "python -i somescript.py" to dump me into the command window with a bunch of code already run. Thanks for blogging this.
Why don't you use the *-i* flag of the intepreter. It fallbacks on the python intpreter when the code is done and with all the local variables availables in local scope.
The reason why? Because I didn't know about it.
Just tried it. It works! Thanks for the tip!
I usually use IPython for this:
import IPython; IPython.embed()
I can't find an easy way to add local variables into that, although there are two features which make it not so much of an issue:
- great history mechanism
- 'run' command to run a script/module in the current environment.
I find I can no longer live with a bare Python shell after having being spoilt with IPython!