3
\$\begingroup\$

A function that asks for user input according to some criteria and again on the same line if the criteria is not met. It requires that escape character sequences be enable.

"""
Ask for user input according to some criteria
and again on the same line if the criteria is
not met
"""

__all__ = ['input_wrong_up_line']


def input_wrong_up_line(input_msg, criteria):
    a = '\033[A'
    input_wrong_msg = a + len(input_msg) * ' '

    while True:
        input_user = input(input_msg)

        if criteria(input_user):
            return input_user

        print(input_wrong_msg + len(input_user) * ' ' + a)


if __name__ == '__main__':
    from colorama import deinit, init

    init()

    try:
        input_wrong_up_line('Exit? [y/ ] ', lambda input_user: input_user == 'y')
    finally:
        deinit()
\$\endgroup\$
2
\$\begingroup\$

Nice, but you’re doing too much work.

\033[J will erase from the cursor position until the end of the screen, which eliminates the need to count characters and print spaces.

(See ANSI escape codes: CSI sequences for additional codes & information.)

So, you just need to move the cursor up one line, clear to end of screen, and not print a newline, leaving the cursor at the “up one line“ position.

print("\033[A\033[J", end='')

Note: if the user input is more than one line of text, moving the cursor up only one line will only result in clearing the last line. Fixing that would require more effort.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy