【问题标题】:Python Shell, Logging Commands for Easy Re-ExecutionPython Shell,记录命令以便于重新执行
【发布时间】:2010-02-11 04:34:35
【问题描述】:

假设我在 python shell 中为我的 Django 应用程序做这样的事情:

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

我想做的是在不离开 shell 的情况下以某种方式隐藏这 3 个命令。目标是如果我稍后重新启动 shell 会话,我可以快速恢复类似的环境。

【问题讨论】:

    标签: python django shell


    【解决方案1】:

    如果可用,Django shell 将使用IPython,它支持持久的历史记录。

    另外,编写一次性脚本is not difficult

    【讨论】:

    • Yy for IPython... 这太棒了。动态对象信息功能真的很酷。我已经写了几个我自己的助手,但这更好。
    【解决方案2】:

    感谢 Ignacio,安装了 IPython:

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

    时髦!

    【讨论】:

    • %logstart 也很有用:它将会话开始后输入的所有内容保存到 ipython_log.py 文件中。
    【解决方案3】:

    Koobz,因为你刚刚成为 ipython 的转换者,有一个很酷的 hack 用于在交互模式下自动导入我的所有应用程序模型:

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

    【讨论】:

    • 这很好,但由于我时髦的项目结构,它目前对我不起作用。尽管如此,它还是促使我创建了一个带有 ipython 别名的自定义 .pythonrc 文件。从现在开始,我将对其进行自定义。回到 Ignacio 的一次性脚本评论。所以谢谢你!
    猜你喜欢
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    相关资源
    最近更新 更多