如何保存 Python 交互式会话? [英] How to save a Python interactive session?
问题描述
我发现自己经常使用 Python 的解释器来处理数据库、文件等——基本上是对半结构化数据进行大量手动格式化.我没有像我希望的那样经常正确地保存和清理有用的位.有没有办法将我的输入保存到 shell 中(数据库连接、变量赋值、很少的 for 循环和一些逻辑)——交互式会话的一些历史?如果我使用类似 script
的东西,我会得到太多的标准输出噪音.我真的不需要腌制所有对象——尽管如果有解决方案可以做到这一点,那就没问题了.理想情况下,我只会留下一个脚本,该脚本与我交互式创建的脚本一样运行,我可以删除不需要的位.是否有执行此操作的软件包或 DIY 方法?
I find myself frequently using Python's interpreter to work with databases, files, etc -- basically a lot of manual formatting of semi-structured data. I don't properly save and clean up the useful bits as often as I would like. Is there a way to save my input into the shell (db connections, variable assignments, little for loops and bits of logic) -- some history of the interactive session? If I use something like script
I get too much stdout noise. I don't really need to pickle all the objects -- though if there is a solution that does that, it would be OK. Ideally I would just be left with a script that ran as the one I created interactively, and I could just delete the bits I didn't need. Is there a package that does this, or a DIY approach?
推荐答案
IPython 如果您喜欢使用交互式会议.例如,对于您的用例,有 %save
魔术命令,您只需输入 %save my_useful_session 10-20 23
即可将输入的第 10 到 20 和 23 行保存到 my_useful_session.py
(以帮助解决这个问题,每一行都以其编号为前缀).
IPython is extremely useful if you like using interactive sessions. For example for your use-case there is the %save
magic command, you just input %save my_useful_session 10-20 23
to save input lines 10 to 20 and 23 to my_useful_session.py
(to help with this, every line is prefixed by its number).
此外,文档指出:
此函数使用与 %history<相同的语法/a> 用于输入范围,然后将行保存为您指定的文件名.
This function uses the same syntax as %history for input ranges, then saves the lines to the filename you specify.
例如,这允许引用较旧的会话,例如
This allows for example, to reference older sessions, such as
%save current_session ~0/
%save previous_session ~1/
查看演示页面上的视频,快速了解功能.
这篇关于如何保存 Python 交互式会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!