簡體   English   中英

如何在 ptpython 控制台中讀取歷史記錄?

[英]How to read history in ptpython console?

我一直在試圖弄清楚如何在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。

謝謝

如果您檢查嵌入的源代碼,那么您會看到選項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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM