首页 文章

如何保存Python交互式会话?

提问于
浏览
364

我发现自己经常使用Python 's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don' t正常保存并尽可能多地清理有用位 . 有没有办法将我的输入保存到shell中(数据库连接,变量赋值,少量循环和逻辑位) - 交互式会话的一些历史记录?如果我使用类似 script 的东西,我会得到太多标准噪音 . 我不需要 . 有没有这样做的包,或DIY方法?

UPDATE :我对这些包装的质量和实用性感到非常惊讶 . 对于那些有类似痒的人:

  • IPython - 应该已经使用了这个年龄,我想到的那种

  • reinteract - 非常令人印象深刻,我想更多地了解可视化,这似乎会在那里闪耀 . 一种gtk / gnome桌面应用程序,用于内嵌图形 . 想象一下混合壳图形计算器迷你蚀 . 来源分布在这里:http://www.reinteract.org/trac/wiki/GettingIt . 在Ubuntu上运行良好,也集成到gnome桌面,Windows和Mac安装程序中 .

  • bpython - 非常酷,很多不错的功能,自动完成(!),倒带,一键击保存到文件,缩进,做得好 . Python源代码分发,从sourceforge中提取了几个依赖项 .

我被转换了,这些真正满足了翻译和编辑之间的需要 .

17 回答

  • 1

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

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

    如果您喜欢使用交互式会话,IPython非常有用 . 例如,对于您的用例,有the %save magic command,您只需输入 %save my_useful_session 10-20 23 以保存输入行10到20和23到 my_useful_session.py (为了帮助它,每行都以其编号为前缀) .

    此外,文件说明:

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

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

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

    请查看the videos on the presentation page以快速了解这些功能 .

  • 135

    有一个way来做 . 将文件存储在 ~/.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平台 .

  • 13

    如果您正在使用IPython,则可以使用带-f参数的魔术函数%history将所有先前命令保存到文件中,p.e:

    %history -f /tmp/history.py
    
  • 62

    安装Ipython后,通过运行命令打开Ipython会话:

    ipython
    

    从命令行,只需运行以下Ipython'magic'命令即可自动记录整个Ipython会话:

    %logstart
    

    这将创建一个唯一命名的.py文件并存储您的会话,以便以后用作交互式Ipython会话或用于您选择的脚本 .

  • 1

    此外,reinteract为您提供了一个类似于笔记本的Python会话界面 .

  • 3

    除了IPython之外,类似的实用程序bpython具有"save the code you've entered to a file"功能

  • 6

    我不得不努力寻找答案,我对iPython环境很新 .

    这会奏效

    如果您的iPython会话看起来像这样

    In [1] : import numpy as np
    ....
    In [135]: counter=collections.Counter(mapusercluster[3])
    In [136]: counter
    Out[136]: Counter({2: 700, 0: 351, 1: 233})
    

    您希望保存从1到135的行,然后在同一个ipython会话中使用此命令

    In [137]: %save test.py 1-135
    

    这将在您当前目录(启动ipython的地方)的test.py文件中保存所有python语句 .

  • 15

    打印和保存输入历史记录(以及可选的输出)有%历史魔力 .

    要将当前会话存储到名为 my_history.py 的文件中:

    >>> %hist -f my_history.py
    

    历史IPython存储您输入的命令及其生成的结果 . 您可以使用上箭头键和下箭头键轻松浏览以前的命令,或以更复杂的方式访问历史记录 .

    您可以使用%history magic函数来检查过去的输入和输出 . 以前会话的输入历史记录保存在数据库中,可以配置IPython以保存输出历史记录 .

    其他几个魔术函数可以使用您的输入历史记录,包括%edit,%rerun,%recall,%macro,%save和%pastebin . 您可以使用标准格式来引用行:

    %pastebin 3 18-20 ~1/1-5
    

    这将从当前会话中获取第3行和第18行到第20行,并从前一个会话中获取第1-5行 .

    查看%history?对于Docstring和更多示例 .

    此外,请务必探索%store magic的功能,以便在IPython中轻量级地保持变量 .

    在IPython的数据库中存储变量,别名和宏 .

    d = {'a': 1, 'b': 2}
    %store d  # stores the variable
    del d
    
    %store -r d  # Refresh the variable from IPython's database.
    >>> d
    {'a': 1, 'b': 2}
    

    要在启动时自动存储存储的变量,请在ipython_config.py中指定 c.StoreMagic.autorestore = True .

  • 84

    只是把另一个暗示放在碗里:Spyder

    enter image description here

    它有历史记录日志和变量资源管理器 . 如果您使用过MatLab,那么您将看到相似之处 .

  • 0

    就Linux而言,可以使用 script 命令来记录整个会话 . 它是 util-linux 包的一部分,因此应该在大多数Linux系统上 . 你可以创建和别名或函数调用 script -c python ,那将是保存到 typescript 文件 . 例如,这是一个这样的文件的重印 .

    $ cat typescript                                                                                                      
    Script started on Sat 14 May 2016 08:30:08 AM MDT
    Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
    [GCC 4.8.2] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> print 'Hello Pythonic World'
    Hello Pythonic World
    >>> 
    
    Script done on Sat 14 May 2016 08:30:42 AM MDT
    

    这里的一个小缺点是 script 会记录所有内容,甚至是换行符,只要你按下退格键等等 . 所以你可能想用 col 来清理输出(见this post on Unix&Linux Stackexchange) .

  • 0

    还有另一个选择--- pyslice . 在“wxpython 2.8 docs演示和工具”中,有一个名为“pyslices”的开源程序 .

    你可以像编辑一样使用它,它也支持像控制台一样使用----像一个具有即时回声的交互式解释器执行每一行 .

    当然,每个块的所有代码块和结果都将自动记录到txt文件中 .

    结果记录在相应的代码块后面 . 很方便 .

    the overview of pyslices

  • 0

    %history 命令很棒,但遗憾的是它赢得了't let you save things that were %paste ' d进入sesh . 要做到这一点,我认为你必须做 %logstart at the beginning(虽然我没有证实这是有效的) .

    我喜欢做的是

    %history -o -n -p -f filename.txt

    这将在每个输入(o,n和p选项)之前保存输出,行号和'>>>' . 请参阅%history here的文档 .

  • 350

    一些评论询问如何一次保存所有IPython输入 . 对于IPython中的%save magic,您可以如下所示以编程方式保存所有命令,以避免提示消息并避免指定输入数字 . currentLine = len(In)-1%save -f my_session 1- $ currentLine

    -f 选项用于强制文件替换, len(IN)-1 显示IPython中的当前输入提示,允许您以编程方式保存整个会话 .

  • 11

    对于使用 spacemacspython-layer 附带的 ipython 的人来说,save magic会产生大量不需要的输出,因为在后台工作的常量自动完成命令如下:

    len(all_suffixes)
    ';'.join(__PYTHON_EL_get_completions('''len'''))
    ';'.join(__PYTHON_EL_get_completions('''all_substa'''))
    len(all_substantives_w_suffixes)
    ';'.join(__PYTHON_EL_get_completions('''len'''))
    ';'.join(__PYTHON_EL_get_completions('''all'''))
    ';'.join(__PYTHON_EL_get_completions('''all_'''))
    ';'.join(__PYTHON_EL_get_completions('''all_w'''))
    ';'.join(__PYTHON_EL_get_completions('''all_wo'''))
    ';'.join(__PYTHON_EL_get_completions('''all_wor'''))
    ';'.join(__PYTHON_EL_get_completions('''all_word'''))
    ';'.join(__PYTHON_EL_get_completions('''all_words'''))
    len(all_words_w_logograms)
    len(all_verbs)
    

    为了避免这种情况,只需保存ipython缓冲区,就像通常保存任何其他缓冲区一样: spc f s

  • 3

    如果使用 bpython ,则默认情况下所有命令历史记录都保存为 ~/.pythonhist .

    要保存命令以供以后重用,您可以将它们复制到python脚本文件:

    $ cp ~/.pythonhist mycommands.py
    

    然后编辑该文件以清理它和put it under Python path(全局或虚拟环境的站点包,当前目录,以* .pth提及,或以其他方式) .

    要将命令包含到shell中,只需从保存的文件中导入它们:

    >>> from mycommands import *
    
  • 0

    我想建议另一种通过linux上的tmux维护python会话的方法 . 你运行tmux,将你自己附加到你打开的会话(如果没有直接打开它后附加) . 执行python并对其执行任何操作 . 然后脱离 Session . 从tmux会话中分离不会关闭会话 . Session 仍然开放 .

    pros of this method: 您可以从任何其他设备附加到此会话(如果您可以ssh您的电脑)

    cons of this method: 此方法在您实际存在python解释器之前不会放弃已打开的python会话使用的资源 .

相关问题