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.
The Django shell will use IPython if available, which supports a persistent history.
Also, writing throwaway scripts is not difficult.
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, 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
精彩评论