5

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?

Amiram
  • 1,227
  • 6
  • 14
artfulrobot
  • 20,637
  • 11
  • 55
  • 81
  • 5
    You can use the [readline module](https://docs.python.org/3/library/readline.html) from the standard library. – Klaus D. Jan 07 '20 at 12:00
  • 2
    [python-prompt-toolkit](https://github.com/prompt-toolkit/python-prompt-toolkit) - it uses readline and more. – furas Jan 07 '20 at 12:44
  • standard [cmd](https://docs.python.org/3/library/cmd.html) also uses `readline` but it may need more changes - every commanad has to be in separated function `do_commandname()`. Similar [cmd2](https://cmd2.readthedocs.io/en/latest/) with more functions. – furas Jan 07 '20 at 12:58

1 Answers1

3

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

artfulrobot
  • 20,637
  • 11
  • 55
  • 81
  • 1
    A bit off topic but the `ptpython` REPL is worth looking at. Written by the same guy and (I think) the project that spawned this one, it's a much better alternative to the standard python shell. Better than IPython imo. – Holloway Jan 08 '20 at 09:31