如何保存Python交互式会话?
我发现自己经常使用Python的解释器来处理数据库、文件等等,基本上就是在手动整理一些半结构化的数据。我并没有像我希望的那样,妥善保存和整理那些有用的部分。有没有办法把我在命令行中输入的内容保存下来(比如数据库连接、变量赋值、小的循环和一些逻辑)——也就是记录一下这个互动会话的历史?如果我用像script
这样的工具,输出的信息太杂了。我其实不需要把所有的对象都保存下来——不过如果有解决方案可以做到这一点,那也可以。理想情况下,我希望能得到一个脚本,它的运行效果和我互动时创建的脚本一样,然后我可以把不需要的部分删掉。有没有这样的工具,或者有什么简单的方法可以实现?
20 个回答
101
有一种方法可以做到这一点。把文件存放在 ~/.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')
请注意,这个方法只适用于 *nix 系统,因为 readline 只在 Unix 平台上可用。
214
来自Andrew Jones的网站(存档链接):
import readline
readline.write_history_file('/home/ahj/history')
458
IPython 非常好用,特别是如果你喜欢用交互式的方式来编程。比如说,你可以使用这个叫做 %save
的魔法命令,只需要输入 %save my_useful_session 10-20 23
就能把第10到20行和第23行的内容保存到 my_useful_session.py
文件里(为了方便,每一行前面都有它的行号)。
而且,文档中提到:
这个功能使用和%history 一样的语法来指定输入的行范围,然后把这些行保存到你指定的文件名中。
这样你就可以方便地引用以前的会话,比如说:
%save current_session ~0/
%save previous_session ~1/
你可以看看演示页面上的视频,快速了解一下它的功能。