Search code examples
pythonpython-3.xrlwrap

Is there a python (3) native equivalent to invoking the script with rlwrap?


I'm using input() to ask a user for a command in a Python (3) CLI script.

I'd like them to be able to press to reuse older commands. For that matter I'd like them to be able to do other basic line editing too.

I can get these features by running rlwrap myscript.py but I'd rather not have to run the wrapper script. (yes I could set up an alias but I'd like to encapsulate it in-script if poss)

Is there a library to enable this (e.g. provide a history/editing aware version of input()) or would I need to start from scratch?


Solution

  • I'm grateful to the answers posted as comments. I tried @furas' suggestion, and it seems to be working fine. Here's a snippet to help others who come here from a search.

    from prompt_toolkit import prompt       
    from prompt_toolkit import PromptSession
    from prompt_toolkit.history import FileHistory
    from os.path import expanduser
    
    myPromptSession = PromptSession(history = FileHistory(expanduser('~/.myhistory')))
    
    while True:
      userInput = myPromptSession.prompt('Enter command')
      print("{}, interesting.".format(userInput))
    
    

    prompt is the main do-ing function, but you don't get any history unless you use a PromptSession. If you don't use the history option, then history is maintained in memory and lost at program exit.

    https://python-prompt-toolkit.readthedocs.io/en/master/index.html