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

1

6

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?

Nozicka answered 7/1, 2020 at 11:57 Comment(3)
You can use the readline module from the standard library.Vena
python-prompt-toolkit - it uses readline and more.Somatic
standard cmd also uses readline but it may need more changes - every commanad has to be in separated function do_commandname(). Similar cmd2 with more functions.Somatic
N
4

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

Nozicka answered 8/1, 2020 at 9:27 Comment(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.Erena

© 2022 - 2024 — McMap. All rights reserved.