python-3.xpython-modulecursesinquirer

Python Inquirer Module: Remove Choices When Done (Using Curses)


NOTE: Although I give a lot of info on Inquirer, I'm pretty sure that most of it won't apply (just being safe). For my actual question about curses, its at the bottom.

I'm using the Inquirer module in Python 3 to allow the user to select a value from a list. I run this:

import inquirer    
choice = inquirer.prompt([inquirer.List("size",message="Which size do you need?",choices=["Large", "Medium", "Small"])

And I'm given this:

[?] What size do you need?: Medium
   Large
 > Medium
   Small

And using the up and down keys, I can change my selection, and hit enter to choose, after which the "choice" variable contains the value I selected. The issue is: Once the selection is done, the choices still show. I want to delete them when done. I'm currently using ANSI Escape Codes to delete the choices from onscreen when done, where x is the number of choices:

import sys    
for i in range (x+1):
    sys.stdout.write('\x1b[1A')
    sys.stdout.write('\x1b[2K')

Which leaves the printed text as:

[?] What size do you need?: Medium

The issue is, ANSI escape codes aren't universal. I want to use a solution that works on all terminals, preferably curses, but curses isn't very friendly to new users, so I was wondering if anyone knew how to use curses to "delete x lines above current position". Thanks!


Solution

  • curses, as such, would erase the whole display (which is probably not what you want). A low-level terminfo/termcap approach might seem promising, but while ECMA-48 does define a sequence (ED, with parameter 1) which erases above the current position, there is no predefined terminfo/termcap capability which corresponds to this. All that you will find there is the capability for erasing to the end of the screen, or erasing the whole screen.

    "ANSI sequences" is an obsolete term. Referring to ECMA-48, you could do

    sys.stdout.write('\x1b[1J')
    

    after moving the cursor to the last location you would like to erase.