如何保存Python交互式会话?

我发现自己经常使用Python的解释器来处理数据库,文件等 - 基本上有很多半结构化数据的手动格式。 我没有按照我的意愿经常保存和清理有用的部分。 有没有办法将我的输入保存到shell(数据库连接,变量赋值,循环和逻辑) - 一些交互式会话的历史记录? 如果我使用类似script东西,我会得到太多的stdout噪音。 我并不需要腌制所有的对象 - 但如果有解决方案可以做到这一点,那就没问题了。 理想情况下,我只剩下一个与我交互创建的脚本一样的脚本,我可以删除我不需要的那些位。 有没有这样做的包装或DIY方法?

更新:我真的很惊讶这些软件包的质量和实用性。 对于那些有类似痒的人:

  • IPython - 应该已经使用了很长时间了,我心里在想什么
  • reinteract - 非常令人印象深刻,我想了解更多关于可视化的知识,这似乎将在那里闪耀。 排列内嵌图形的gtk / gnome桌面应用程序。 想象一下混合外壳+图形计算器+迷你月食。 来源分布在这里:http://www.reinteract.org/trac/wiki/GettingIt。 在Ubuntu上构建得很好,也集成到gnome桌面,Windows和Mac安装程序中。
  • bpython - 非常酷,很多不错的功能,自动完成(!),倒带,一个按键保存到文件,缩进,做得很好。 Python源代码分发,从sourceforge中提取了一些依赖关系。
  • 我被转换了,这些确实填补了翻译和编辑之间的需求。


    如果您喜欢使用交互式会话,IPython非常有用。 例如,对于您的用例,有%save magic命令,您只需输入%save my_useful_session 10-20 23将输入行10到20和23保存到my_useful_session.py (为了解决这个问题,每行都以其前缀为数)。

    此外,该文件指出:

    此函数对输入范围使用与%history相同的语法,然后将行保存为您指定的文件名。

    这允许例如引用较旧的会话,例如

    %save current_session ~0/
    %save previous_session ~1/
    

    查看演示页面上的视频以快速浏览功能。


    http://www.andrewhjon.es/save-interactive-python-session-history

    import readline
    readline.write_history_file('/home/ahj/history')
    

    有办法做到这一点。 将文件存储在~/.pystartup ...

    # Add auto-completion and a stored history file of commands to your Python
    # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
    # bound to the Esc key by default (you can change it - see readline docs).
    #
    # Store the file in ~/.pystartup, and set an environment variable to point
    # to it:  "export PYTHONSTARTUP=/home/user/.pystartup" in bash.
    #
    # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
    # full path to your home directory.
    
    import atexit
    import os
    import readline
    import rlcompleter
    
    historyPath = os.path.expanduser("~/.pyhistory")
    
    def save_history(historyPath=historyPath):
        import readline
        readline.write_history_file(historyPath)
    
    if os.path.exists(historyPath):
        readline.read_history_file(historyPath)
    
    atexit.register(save_history)
    del os, atexit, readline, rlcompleter, save_history, historyPath
    

    然后在shell中设置环境变量PYTHONSTARTUP (例如在~/.bashrc ):

    export PYTHONSTARTUP=$HOME/.pystartup
    

    您也可以添加这个来免费自动完成:

    readline.parse_and_bind('tab: complete')
    

    请注意,这只适用于* nix系统。 由于readline只能在Unix平台上使用。

    链接地址: http://www.djcxy.com/p/22739.html

    上一篇: How to save a Python interactive session?

    下一篇: Download affy annotation file with python