You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何查看Python交互式解释器的历史执行命令记录

Python交互式解释器重进后查看历史命令方法

临时查看方法

无需额外配置,重新进入Python解释器后直接执行以下代码即可输出所有历史执行命令:

import readline
for i in range(readline.get_current_history_length()):
    print(readline.get_history_item(i + 1))

如果你不想进入Python解释器,也可以直接在终端查看默认存储历史的文件:

cat ~/.python_history

永久配置快捷history命令

如果希望像示例一样输入类history命令直接出结果,可以通过配置Python启动项实现:

  • 在家目录新建.pythonstartup.py文件,写入如下内容:
import readline
import atexit
import os

# 加载历史记录
history_file = os.path.expanduser("~/.python_history")
if os.path.exists(history_file):
    readline.read_history_file(history_file)

# 退出时自动保存新的历史记录
atexit.register(readline.write_history_file, history_file)

# 自定义历史查询命令
def history():
    for i in range(readline.get_current_history_length()):
        print(readline.get_history_item(i + 1))
  • 在你当前使用的shell配置文件(常用的为~/.bashrc、~/.zshrc)中添加环境变量:
export PYTHONSTARTUP=~/.pythonstartup.py
  • 执行source 对应配置文件路径让配置生效,之后重新进入Python解释器,直接执行history()即可得到你预期的输出效果。

补充:如果你使用的是IPython环境,无需额外配置,直接执行魔法命令%history即可查看所有历史。

内容的提问来源于stack exchange,提问作者rzlvmp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:15:08