代码之家  ›  专栏  ›  技术社区  ›  unmounted

如何保存Python交互式会话?

  •  374
  • unmounted  · 技术社区  · 17 年前

    我发现自己经常使用Python的解释器来处理数据库、文件等——基本上是对半结构化数据进行大量手动格式化。我没有像我想的那样经常保存和清理有用的部分。有没有办法将我的输入保存到shell中(db连接、变量分配、小循环和逻辑位)——交互式会话的一些历史记录?如果我使用类似 script 我的噪音太大了。我真的不需要对所有对象进行pickle处理——尽管如果有一个解决方案可以做到这一点,那也没关系。理想情况下,我只需要留下一个脚本,作为我交互创建的脚本运行,我可以删除不需要的部分。有没有这样的套餐,或者DIY方式?

    18 回复  |  直到 5 年前
        1
  •  431
  •   tutuDajuju    9 年前

    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 以快速了解这些功能。

        2
  •  186
  •   Roberto Z    14 年前

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

    import readline
    readline.write_history_file('/home/ahj/history')
    
        3
  •  96
  •   brandizzi    11 年前

    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
    

    然后设置环境变量 PYTHONSTARTUP 在你的壳中(例如在 ~/.bashrc

    export PYTHONSTARTUP=$HOME/.pystartup
    

    您还可以添加此项以免费获取自动完成:

    readline.parse_and_bind('tab: complete')
    

        4
  •  77
  •   nachouve N Randhawa    11 年前

    如果您正在使用 IPython 您可以使用magic函数将以前的所有命令保存到一个文件中 %history

    %history -f /tmp/history.py
    
        5
  •  21
  •   webappzero    11 年前

    安装后 Ipython

    ipython
    

    在命令行中,只需运行以下Ipython“magic”命令即可自动记录整个Ipython会话:

    %logstart
    

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

        6
  •  14
  •   Ned Batchelder    17 年前

    而且 reinteract 为Python会话提供类似笔记本的接口。

        7
  •  11
  •   user JaredPar    12 年前

    bpython 具有“将输入的代码保存到文件”功能

        8
  •  9
  •   Somum    12 年前

    我不得不努力寻找答案,我对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
    

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

        9
  •  4
  •   Alexander    10 年前

    有%history magic用于打印和保存输入历史(以及可选的输出)。

    my_history.py :

    >>> %hist -f my_history.py
    

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

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

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

    这将占用当前会话的第3行和第18至20行,以及上一会话的第1至5行。

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

    另外,一定要了解 %store magic 用于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}
    

    c.StoreMagic.autorestore = True

        10
  •  3
  •   Norfeldt    10 年前

    只是在碗里放另一个建议: Spyder

    enter image description here

    历史记录 变量浏览器

        11
  •  3
  •   Community Mohan Dere    9 年前

    这个 %history 命令非常棒,但不幸的是,它不允许您将%paste'd的内容保存到sesh中。要做到这一点,我认为你必须这样做 %logstart at the beginning (虽然我还没有确认这是有效的)。

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

    将保存输出、行号和“>&燃气轮机>'在每个输入之前(o、n和p选项)。查看文档以了解%history here .

        12
  •  2
  •   Community Mohan Dere    9 年前

    script 命令来记录整个会话。它是 util-linux 包so应该在大多数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
    

    这里的小缺点是 剧本 记录所有内容,甚至是换行,无论何时您点击backspaces等,所以您可能需要使用 col 要清理输出(请参阅 this post on Unix&Linux Stackexchange ) .

        13
  •  1
  •   fandyst    13 年前

    还有另一种选择——pyslice。 在“Wxpython2.8文档演示和工具”中,有一个名为“PyStices”的开源程序。

    您可以像编辑器一样使用它,它还支持像控制台一样使用它——像交互式解释器一样立即执行每一行。

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

    结果记录在相应代码块的后面。非常方便。

    the overview of pyslices

        14
  •  1
  •   Aidas Bendoraitis Rob Sanderson    9 年前

    如果你使用 比顿 ,默认情况下,所有命令历史记录都保存到 ~/.pythonhist .

    $ cp ~/.pythonhist mycommands.py
    

    然后编辑该文件以将其清理并删除 put it under Python path

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

    >>> from mycommands import *
    
        15
  •  1
  •   user2314737    6 年前

    IPython ,我先用

    In [2]: %hist
    

    查看我过去的代码。我选择要保存的块,然后将其粘贴到文件中 my_file.py 使用 %%file 魔术 %%writefile )

    In [3]: %%file my_file.py
       ...: # paste code here 
       ...:  
       ...:  
    

    最后打了两次回击。

    要附加到文件,请使用选项 -a : %%file -a my_file.py .

    如果需要,我可以使用感叹号在底层命令行中列出、编辑文件等

    In [5]: !ls -l my_file.py
    In [6]: !vi my_file.py
    
        16
  •  0
  •   E. F. Haghish    10 年前

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

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

        17
  •  0
  •   Kaan E.    9 年前

    适用于使用 spacemacs ipython 随附 python-layer

    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

        18
  •  0
  •   Myonaiz mpruchni    9 年前

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

    这种方法的优点: 您可以从任何其他设备连接到此会话(如果您可以使用ssh连接pc)

    这种方法的缺点: 在实际存在python解释器之前,此方法不会放弃打开的python会话所使用的资源。

        19
  •  0
  •   Paul    7 年前

    :

    1. 在XWindows中,从Xfce终端应用程序运行iPython
    2. 点击 Terminal save contents 在下拉列表中

        20
  •  -1
  •   user13518412    6 年前

    您可以使用内置函数open:我在所有的应用程序中都使用它 我需要在其中存储一些历史记录的程序(包括计算器等) 例如:

    #gk-test.py or anything else would do
    try: # use the try loop only if you haven't created the history file outside program
        username = open("history.txt").readline().strip("\n")
        user_age = open("history.txt").readlines()[1].strip("\n")
    except FileNotFoundError:
        username = input("Enter Username: ")
        user_age = input("Enter User's Age: ")
        open("history.txt", "w").write(f"{username}\n{user_age}")
    #Rest of the code is secret! try it your own!
    

    我要感谢所有喜欢我评论的人!谢谢你阅读这篇文章!