views:

148

answers:

3

Say I do something like this in a python shell for my Django app:

>>>from myapp.models import User
>>>user = User.objects.get(pk=5)
>>>groups = user.groups.all()

What I'd like to do is stash these 3 commands somehow without leaving the shell. The goal being I can quickly restore a similar environment if I restart the shell session later.

+2  A: 

The Django shell will use IPython if available, which supports a persistent history.

Also, writing throwaway scripts is not difficult.

Ignacio Vazquez-Abrams
Yay for IPython... this rocks. Dynamic object information features are really cool. I had written a couple of my own helpers but this is so much nicer.
Koobz
+1  A: 

So thanks to Ignacio, with IPython installed:

>>>from myapp.models import User
>>>user = User.objects.get(pk=5)
>>>groups = user.groups.all()
>>>#Ipython Tricks Follow
>>>hist #shows you lines in your history
>>>edit 1:3 # Edit n:m lines above in text editor. I save it as ~/testscript
>>>run ~/testscript

Groovy!

Koobz
%logstart is also useful: it saves everything entered since the beginning of the session into an ipython_log.py file.
EOL
+1  A: 

Koobz, since you've just become a recent convert to ipython, there's a cool hack I use for automatically importing all my application models in interactive mode:

#!/bin/env python
# based on http://proteus-tech.com/blog/code-garden/bpython-django/
try:
    from django.core.management import setup_environ
    import settings
    setup_environ(settings)
    print "imported django settings"
    try:
        exec_strs = ["from %s.models import *"%apps for apps in settings.INSTALLED_APPS if apps not in ['django_extensions']]
        for x in exec_strs:
            try:
                exec(x)
            except:
                print 'not imported for %s' %x
        print 'imported django models'
    except:
        pass
except:
    pass

Then I just alias: ipython -i $HOME/.pythonrc

Jeff Bauer
This is nice but it doesn't currently work for me because of my funky project structure. Still, it did spur me into creating a custom .pythonrc file, with an ipython alias. I'm just going to customize it from now on. Goes back to Ignacio's throwaway scripts comment. So thanks for that!
Koobz