如何在ptpython控制台中查看历史记录?

4

我一直在尝试找出如何在ptpython控制台中保存和读取Python命令的历史记录,但是一直没有成功。到目前为止,我的所有努力都是基于这个答案的变化。然而,我仍然无法读取我的历史记录。

我希望能够简单地按下箭头,浏览以前控制台会话中的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。
谢谢。

对于我来说,你运行了 sys.exit(embed()) ,所以在这一行后它不能运行代码,因此无法读取历史记录。 你必须在 sys.exit(embed()) 前读取它。 如果你在 sys.exit(embed()) 后面加上 print() ,那么你会发现它永远不会被打印。 - furas
可能有帮助的提示:如果用户在二进制文件中安装了 ptpython ,则保存历史记录的潜在目录包括 .local/share/ptpython~/.ptpython - butla
1个回答

5
如果您查看嵌入的源代码,您会看到选项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:
    history_path = os.path.expanduser("~/.ptpython/history")
    embed(globals(), locals(), history_filename=history_path)

顺便提一下: 如果文件夹 ~/.ptpython 不存在,则需要在运行代码之前创建它。

编辑(2022):

import os

try:
    from ptpython.repl import embed
except ImportError:
    print('ptpython is not available: falling back to standard prompt')
else:
    history_dir  = os.path.expanduser("~/.ptpython")
    history_path = os.path.join(history_dir, "history")
    
    if not os.path.exists(history_path):
        os.makedirs(history_dir, exist_ok=True)  # create folder if not exist
        open(history_path, 'a').close()          # create empty file
        
    embed(globals(), locals(), history_filename=history_path)

我认为这个可以工作!让我使用一下来确保一切都正常运行,然后我可以将其标记为正确。 - gr1zzly be4r

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接