Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make it so taking input does not interrupt program execution

I need to take input from the user while being able to print, kind of like threading.

For example:

1 +----------+
2 |Input here|
3 |          |
4 |          |
5 |          |
6 +----------+

Normally the user would have to input something before printing lines 3 to 6 is executed.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is using the "standard" library curses

You might need to do
pip install windows-curses
for this to work on Windows, otherwise you might get ModuleNotFoundError: No module named '_curses'


import curses

def main(stdscr):
    curses.curs_set(0)
    stdscr.clear()
    stdscr.refresh()

    text = "Input here"
    y, x = 0, 0
    
    while True:
        stdscr.clear()


        stdscr.addstr("\n")
        square = f"+{'-' * (len(text) + 2)}+\n"
        square += f"| {text} |\n"
        square += f"|{' ' * (len(text) + 2)}|\n" * 4
        square += f"+{'-' * (len(text) + 2)}+"
        stdscr.addstr(y, x, square)

        stdscr.refresh()

        key = stdscr.getch()
        
        if key == 8:
            text = text[:-1]
        elif key == 10:
            break
        elif key >= 32 and key <= 126:
            text += chr(key)
        
    return text

if __name__ == "__main__":
    user_input = curses.wrapper(main)
    print(f"User input was: {user_input}")

Very simple but it shows what you can do.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading