Search code examples
pythonprintingcurses

Python print messed up after calling curses wrapper


I am having a problem with curses library in Python. Consider the following code:

def main(stdscr):

    print('Hello World!!')
    create_screen()
    curses.endwin()

if __name__ == "__main__":
    curses.wrapper(main)

The problem is every text printed by "print" function is messed up even before calling "create_screen()" function which initiates the screen by "curses.initscr()"


Solution

  • You can use print and input normally before and after your program uses curses. Also, you do not have to put all your code into main, and you don't have to pass the main function to curses, either. main is just a function like any other. Check out this simple example:

    import curses, time
    
    def incurses(stdscr):
        stdscr.addstr(0, 0, "Exiting in ")
        stdscr.addstr(2, 0, "Hello World from Curses!")
        for i in range(5, -1, -1):
            stdscr.addstr(0, 11, str(i))
            stdscr.refresh()
            time.sleep(1)
        curses.endwin()
    
    def main():
        print('Hello World!!')
        choice = input("Start Curses Program? ")
        if choice == "yes":
            curses.wrapper(incurses)
        print("After curses")
    
    if __name__ == "__main__":
        main()
    

    This prints and asks for user input, then shows a curses screen, then goes back into "normal" printing mode.