Show default value for editing on Python input possible?
The standard library functions input()
and raw_input()
don't have this functionality. If you're using Linux you can use the readline
module to define an input function that uses a prefill value and advanced line editing:
import readline
def rlinput(prompt, prefill=''):
readline.set_startup_hook(lambda: readline.insert_text(prefill))
try:
return input(prompt) # or raw_input in Python 2
finally:
readline.set_startup_hook()
Is it possible to create an input with an editable default value?
You can test whether the user has inputted anything then if they haven't replace it:
default_val = 'Default answer'
inp = input("Enter a string (default value is: '"+default_val+"'): ")
if not inp:
inp = default_val
print(inp)
This outputs:
Enter a string (default value is: 'Default answer'):
Default answer
or
Enter a string (default value is: 'Default answer'): Different answer
Different answer
Python: Get user input by letting user edit default value
Yes, there is a way. Use readline
import readline
defaultText = 'I am the default value'
readline.set_startup_hook(lambda: readline.insert_text(defaultText))
res = raw_input('Edit this:')
print res
Note that this is not a terribly portable solution, and I've only tested it on Linux :)
Pre-initialize raw_input with default value
I actually found an answer myself after some more Googling. It can be done with raw_input
when using the readline
module as follows:
import readline
def pre_input_hook():
readline.insert_text('DefaultValue')
readline.redisplay()
readline.set_pre_input_hook(pre_input_hook)
while True:
line = raw_input('Prompt ("stop" to quit): ')
if line == 'stop':
break
print 'ENTERED: "%s"' % line
Or, to wrap it all in an easier-to-handle function based on jonrsharpe's comment:
import readline
DEFAULT_TEXT = ''
def default_hook():
"""Insert some default text into the raw_input."""
readline.insert_text(default_hook.default_text)
readline.redisplay()
readline.set_pre_input_hook(default_hook)
def raw_input_default(prompt, default=None):
"""Take raw_input with a default value."""
default_hook.default_text = DEFAULT_TEXT if default is None else default
return raw_input(prompt)
python console, better than raw_input(), how to offer editable default values?
I suggest looking into readline / pyreadline, or even possibly curses.
How to give the user pre-filled input to edit and then approve? Python
We can do this in a Tkinter window. Which may not be what you are looking for, but is a solution using the standard library. Here is some example code that creates a window with a default string. You can edit the string. When the return key is pressed, the string in the window is read.
from tkinter import Tk, LEFT, BOTH, StringVar
from tkinter.ttk import Entry, Frame
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Entry")
self.pack(fill=BOTH, expand=1)
self.contents = StringVar()
# give the StringVar a default value
self.contents.set('test')
self.entry = Entry(self)
self.entry.pack(side=LEFT, padx=15)
self.entry["textvariable"] = self.contents
self.entry.bind('<Key-Return>', self.on_changed)
def on_changed(self, event):
print('contents: {}'.format(self.contents.get()))
return True
def main():
root = Tk()
ex = Example(root)
root.geometry("250x100+300+300")
root.mainloop()
if __name__ == '__main__':
main()
Related Topics
How to Execute Raw SQL in Flask-Sqlalchemy App
How to Make Sure If Some HTML Elements Are Loaded for Selenium + Python
How to Make Separator in Pandas Read_CSV More Flexible Wrt Whitespace, for Irregular Separators
Python Functions Call by Reference
Python: Access Class Property from String
Python Script to Do Something at the Same Time Every Day
Find the Max of Two or More Columns with Pandas
Python:List Index Out of Range Error While Iteratively Popping Elements
Truth Value of a String in Python
How to Find Children of Nodes Using Beautifulsoup
How to Prevent Numbers Being Changed to Exponential Form in Python Matplotlib Figure
Combine Several Images Horizontally with Python
Pandas: Convert Categories to Numbers
Make Virtualenv Inherit Specific Packages from Your Global Site-Packages