"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Create a Prefilled Input Function in Python for Linux Systems?

How to Create a Prefilled Input Function in Python for Linux Systems?

Published on 2024-11-09
Browse:638

How to Create a Prefilled Input Function in Python for Linux Systems?

Input Editing in Python

Python's input() and raw_input() functions don't natively allow for prefilled input editing. However, in Linux systems, the readline module can be utilized to create an rlinput function that provides this functionality.

The rlinput function takes two arguments:

  • prompt: The prompt to display to the user.
  • prefill: The initial value to display in the input field.

Here's an example of how to use this function:

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()

folder = rlinput('Folder name: ', 'Download')

This code will display the following prompt to the user:

Folder name: Download

If the user presses Enter without typing anything, the default value "Download" will be returned. If they want to edit it to "Downloads," they can simply add the letter 's' and press Enter.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3