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

gr1*_*e4r 4 python console python-3.x ptpython

我一直试图弄清楚如何在控制台中保存和读取 Python 命令的历史记录ptpython,但一直无法做到这一点。到目前为止,我所有的努力都是这个答案的变体。然而,我仍然无法阅读我的历史。

\n

我只是希望能够按\xe2\x86\x91\xe2\x86\x93箭头来浏览上一个控制台会话(而不是我所在的当前控制台会话)中的 Python 命令。这是我的$PYTHONSTARTUP文件中当前的内容:

\n
# Add auto-completion and a stored history file of commands to your Python\n# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is\n# bound to the Esc key by default (you can change it - see readline docs).\n#\n# Store the file in ~/.pystartup, and set an environment variable to point\n# to it:  "export PYTHONSTARTUP=/home/user/.pystartup" in bash.\n#\n# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the\n# full path to your home directory.\n\nimport atexit\nimport os\nimport readline\nimport rlcompleter\nimport sys\ntry:\n    from ptpython.repl import embed\nexcept ImportError:\n    print(\'ptpython is not available: falling back to standard prompt\')\nelse:\n    sys.exit(embed(globals(), locals()))\n\nhistoryPath = os.path.expanduser("~/.ptpython/history")\n\ndef save_history(historyPath=historyPath):\n   import readline\n   readline.write_history_file(historyPath)\n\nif os.path.exists(historyPath):\n   readline.read_history_file(historyPath)\n\natexit.register(save_history)\nreadline.parse_and_bind(\'tab: complete\')\ndel os, atexit, readline, rlcompleter, save_history, historyPath\n
Run Code Online (Sandbox Code Playgroud)\n

我的$PYTHONSTARTUP变量是:

\n
$ echo $PYTHONSTARTUP \n/Users/[redacted]/.pystartup\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n

谢谢

\n

fur*_*ras 5

如果您检查嵌入的源代码,那么您会看到选项history_filename=

embed(globals(), locals(), history_filename=historyPath)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)

顺便说一句:如果文件夹~/.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)
Run Code Online (Sandbox Code Playgroud)