2

I've been trying to figure out how to get save and read in the history of my Python commands in a ptpython console, but haven't been able to do so. All of my efforts have so far been variations of this answer. However, I still am not able to read in my history.

I would simply like to be able to press the and arrows to go through my Python commands from a previous console session (not the current console session that I'm in). Here's what I currently have in my $PYTHONSTARTUP file:

# 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

And my $PYTHONSTARTUP variable is:

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

I'm on Python 3.7.3, macOS 10.14.6, and ptpython 2.0.4.

Thanks

MarianD
  • 11,249
  • 12
  • 32
  • 51
gr1zzly be4r
  • 1,942
  • 1
  • 15
  • 31
  • as for me you runs `sys.exit(embed())` so it can't runs code after this line so it can't read history. You would have to read it before `sys.exit(embed())`. If you put `print()` after `sys.exit(embed())` then you will see it is never printed. – furas Jan 27 '20 at 18:20

1 Answers1

4

If you check source code for embed then you see option 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)

BTW: If folder ~/.ptpython doesn't exists then you will have to create it before run code.

Gringo Suave
  • 27,899
  • 6
  • 81
  • 73
furas
  • 119,752
  • 10
  • 94
  • 135
  • I think that this worked! Let me use it for a bit to make sure that everything is functioning correctly, and then I can mark it as correct. – gr1zzly be4r Jan 27 '20 at 19:09