如何在ptpython控制台中读取历史记录?

2024-06-16 09:55:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在试图弄清楚如何在ptpython控制台中保存和读取Python命令的历史记录,但一直未能做到这一点。迄今为止,我所有的努力都是this answer的变化。然而,我仍然无法阅读我的历史

我只想能够按下箭头,用于浏览上一个控制台会话中的Python命令(而不是我所处的当前控制台会话)。以下是我当前在$PYTHONSTARTUP文件中的内容:

# 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
import sys
try:
    from ptpython.repl import embed
except ImportError:
    print('ptpython is not available: falling back to standard prompt')
else:
    sys.exit(embed(globals(), locals()))

historyPath = os.path.expanduser("~/.ptpython/history")

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)
readline.parse_and_bind('tab: complete')
del os, atexit, readline, rlcompleter, save_history, historyPath

我的$PYTHONSTARTUP变量是:

$ echo $PYTHONSTARTUP 
/Users/[redacted]/.pystartup

我使用的是Python 3.7.3、macOS 10.14.6和ptpython 2.0.4

谢谢


Tags: andthetopathinimportreadlineos
1条回答
网友
1楼 · 发布于 2024-06-16 09:55:45

如果检查源代码中的embed,则会看到选项history_filename=

embed(globals(), locals(), history_filename=historyPath)

import os

try:
    from ptpython.repl import embed
except ImportError:
    print('ptpython is not available: falling back to standard prompt')
else:
    historyPath = os.path.expanduser("~/.ptpython/history")
    embed(globals(), locals(), history_filename=historyPath)

顺便说一句:如果文件夹~/.ptpython不存在,那么您必须在运行代码之前创建它

相关问题 更多 >