[Tutor] Interactive editing of variables.
Steven D'Aprano
steve at pearwood.info
Tue Jun 4 04:49:17 EDT 2019
Hi Sean,
On Sat, Jun 01, 2019 at 12:53:00PM +1000, mhysnm1964 at gmail.com wrote:
> I have had a look and cannot find an example where I can interactively edit
> a content of a variable at the command line. I do not want to use GUI at
> all. As this is a simple program only requiring CLI. I have no problems
> showing the prompt, but cannot insert text into the edit (input) area. Any
> ideas?
Let me see if I understand what you are asking for.
The built-in function "input()" takes one argument, the prompt, and lets
the user type a response. So if I run the function:
input("What is your name?")
the terminal will display the prompt, and put the text cursor next to
it. That is how things work now.
I think what you are asking for is the ability to pass a second argument
to the function, like this:
input("What is your name?", "George")
and the terminal will display the prompt, then place the word "George"
next to the prompt in the edit-zone. The user (you) can then backspace
over the word and type something new, or otherwise edit it.
Is that what you want?
If so, then on Linux or Unix systems, you can do this:
import readline
def myinput(prompt='', initial=''):
readline.set_startup_hook(lambda: readline.insert_text(initial))
try:
response = input(prompt)
finally:
readline.set_startup_hook(None)
return response
The bad news is that this only works on Linux and other Unix systems
with readline installed (which nearly all of them do). It won't work
under Windows.
But if you install the third-party library pyreadline, you *may* be able
to use that instead:
import pyreadline as readline
and the rest might work. (I don't have Windows and can't try it.)
--
Steven
More information about the Tutor
mailing list