将Python解释器历史导出到文件?

26 投票
7 回答
25372 浏览
提问于 2025-04-17 07:55

很多时候,我会使用Python解释器来检查变量和逐步执行命令,直到我真正写入文件为止。然而到最后,我在解释器中大约有30条命令,我需要把它们复制粘贴到一个文件里才能运行。有办法把Python解释器的历史记录导出或写入文件吗?

比如说:

>>> a = 5
>>> b = a + 6
>>> import sys
>>> export('history', 'interactions.py') 

然后我可以打开interactions.py文件,查看里面的内容:

a = 5
b = a + 6
import sys

7 个回答

11

自从这个问题被提出来的8年里,很多事情都发生了变化。

从Python 3.4开始,历史记录会自动保存到一个叫~/.python_history的文本文件里。

如果你想关闭这个功能或者想了解更多,可以看看以下链接:

当然,正如许多人提到的,IPython有很棒的功能,可以保存、搜索和处理历史记录。你可以通过%history?了解更多。

12

如果你在使用Linux或Mac,并且安装了readline库,你可以把下面的内容添加到一个文件里,然后在你的.bash_profile中导出它,这样你就可以同时拥有自动补全和历史记录的功能。

# python startup file
import readline
import rlcompleter
import atexit
import os
# tab completion
readline.parse_and_bind('tab: complete')
# history file
histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
try:
    readline.read_history_file(histfile)
except IOError:
    pass
atexit.register(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter

导出命令:

export PYTHONSTARTUP=path/to/.pythonstartup

这样做会把你的Python控制台的历史记录保存在~/.pythonhistory这个文件里。

26

IPython 是一个非常好用的工具,特别适合喜欢交互式操作的人。如果你想保存你的操作记录,可以使用 save 命令,比如输入 save my_useful_session 10-20 23,这样就可以把第 10 到 20 行和第 23 行的内容保存到 my_useful_session.py 文件里。(为了方便,每一行前面都有行号)

你可以去文档页面看一些视频,快速了解这个工具的功能。

::或者::

还有一种 方法 可以做到这一点。把文件存放在 ~/.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

你还可以添加一些设置,让自动补全功能免费使用:

readline.parse_and_bind('tab: complete')

请注意,这个功能只在 *nix 系统上有效,因为 readline 只在 Unix 平台上可用。

撰写回答