gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:09:23 24 4
gpt4 key购买 nike

我一直在尝试弄清楚如何在 ptpython 控制台中保存和读取我的 Python 命令的历史记录,但没能做到。到目前为止,我所有的努力都是 this answer 的变体。 .但是,我仍然无法读取我的历史记录。

我只是希望能够按 箭头来浏览我之前控制台 session 中的 Python 命令(不是 我所在的当前控制台 session )。这是我目前在我的 $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。

谢谢

最佳答案

如果您检查 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:
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)

关于python - 如何在 ptpython 控制台中读取历史记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59936089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com