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()
asked May 31, 2021 at 16:59
\$\endgroup\$

1 Answer 1

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円[A033円[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.

answered May 31, 2021 at 18:59
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.