0

I'm working on a Python program that involves a real-time countdown timer and allows the user to input a value inline with the timer using the curses library. However, I'm facing some issues with the code and need some assistance in fixing it.

The current code is as follows:

import time
import threading
import curses

def countdown_timer(stdscr, seconds, inputs):
    stdscr.clear()

    for remaining_time in range(seconds, -1, -1):
        stdscr.addstr(0, 0, f"Time Left: {remaining_time} seconds - Input: {inputs[0]}")
        stdscr.refresh()

        # Check if user input is available
        if stdscr.getch() != -1:
            break

        time.sleep(1)

    stdscr.addstr(0, 0, "Time's up! - Input: " + inputs[0])
    stdscr.refresh()

# Main program
inputs = [""]

# Initialize curses
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(True)

# Start countdown timer
timer_thread = threading.Thread(target=countdown_timer, args=(stdscr, 45, inputs))
timer_thread.start()

# Get user input
while True:
    key = stdscr.getch()
    if key == ord('\n'):
        break
    elif key != -1:
        inputs[0] += chr(key)

# Wait for the timer to finish
timer_thread.join()

# Clean up curses
curses.echo()
stdscr.keypad(False)
curses.endwin()

# Print the input
print(f"Input: {inputs[0]}")

The issues I'm encountering are as follows:

  1. The countdown timer is not working properly. It either skips numbers or does not display the countdown in real-time.
  2. The user input is not being captured correctly. The program does not allow the user to input a value inline with the timer.
  3. The program is not handling the curses library correctly. There might be an issue with the initialization or cleanup process.

In addition to these issues, I would like to clarify that I need the timer to change every second in real-time and be displayed next to the user input. For example, the expected output should be:

Time Left: [remaining_time] seconds - Input: [user input]

I would appreciate any guidance or suggestions on how to fix these issues and make the real-time countdown timer and user input work seamlessly using the curses library. Thank you in advance for your help!

edge selcuk
  • 109
  • 6
  • Your example uses curses in a thread, but has initialized it outside that thread. So both input and output will be subject to races, etc. – Thomas Dickey Jul 02 '23 at 08:34
  • This is one of several duplicates: [Workaround for ncurses multi-thread read and write](https://stackoverflow.com/questions/53809310/workaround-for-ncurses-multi-thread-read-and-write) – Thomas Dickey Jul 02 '23 at 08:35

0 Answers0