pythonshell,记录命令以便于重新执行

pythonshell,记录命令以便于重新执行,python,django,shell,Python,Django,Shell,假设我在Pythonshell中为Django应用程序执行类似操作: >>>from myapp.models import User >>>user = User.objects.get(pk=5) >>>groups = user.groups.all() 我想做的是在不离开shell的情况下以某种方式隐藏这3条命令。目标是,如果稍后重新启动shell会话,我可以快速恢复类似的环境。Django shell将使用(如果可用),它支持持久

假设我在Pythonshell中为Django应用程序执行类似操作:

>>>from myapp.models import User
>>>user = User.objects.get(pk=5)
>>>groups = user.groups.all()
我想做的是在不离开shell的情况下以某种方式隐藏这3条命令。目标是,如果稍后重新启动shell会话,我可以快速恢复类似的环境。

Django shell将使用(如果可用),它支持持久历史记录


还有,编写一次性脚本。

多亏了安装了IPython的Ignacio:

>>>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

太棒了

Koobz,由于您最近刚刚转换为ipython,因此我使用了一个很酷的方法在交互模式下自动导入我的所有应用程序模型:

#!/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

然后我只是别名:
ipython-I$HOME/.pythonrc

Yay for ipython。。。这个石头。动态对象信息功能非常酷。我自己写了几个助手,但这太好了。%logstart也很有用:它会将会话开始后输入的所有内容保存到一个ipython_log.py文件中。这很好,但由于我的项目结构很古怪,目前对我不起作用。尽管如此,它还是促使我创建了一个带有ipython别名的自定义.pythonrc文件。从现在起,我将对其进行定制。返回到Ignacio的一次性脚本注释。所以谢谢你!