0

Currently, the code waits for user input before printing the next number. I want the code to print numbers continuously without being interrupted by user input, but still allow the user to enter a number and have it displayed in the output. How can I do this?

import time
for i in range(0,100000):
    time.sleep(1)
    print(i)
    input('Enter: ')

i found this code Print and input at the same time python multithread

import curses

history = []
def pprint(text):
    global history
    history.insert(0, text)
    if len(history) == int(curses.LINES) - 2:
        history = history[:int(curses.LINES) - 3]
    quote_window.clear()
    for his in history[::-1]:
        quote_window.addstr(his + "\n")
        quote_window.refresh()

stdscr = curses.initscr()

curses.noecho()
curses.cbreak()
stdscr.keypad(True)
curses.curs_set(0)

if curses.has_colors():
    curses.start_color()

curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)

stdscr.addstr("Server", curses.A_REVERSE)
stdscr.chgat(-1, curses.A_REVERSE)

quote_window = curses.newwin(curses.LINES-2, curses.COLS, 1, 0)
input_window = curses.newwin(curses.LINES, curses.COLS, curses.LINES-1, 0)
input_window.bkgd(curses.color_pair(1))
input_window.addstr(">> ")
stdscr.noutrefresh()
quote_window.noutrefresh()
input_window.noutrefresh()

curses.doupdate()

comm = ""
while True:
    key = input_window.getch()
    if key == 10:
        pprint(comm)
        input_window.clear()
        input_window.addstr(">> ")
        comm = ""
    else:
        input_window.addstr(chr(key))
        comm += chr(key)

curses.nocbreak()
curses.echo()
curses.curs_set(1)
curses.endwin()

which works wonderfully and the ui looks really great but i cant copy i cant paste i cant backspace it does some weird characters is there some way to fix this code or new code that has the same ui look?

Ryan Zhang
  • 1,856
  • 9
  • 19

1 Answers1

0

You're right about how you can open a new thread and use that to print numbers continually. Simply move the code that prints numbers into a function and put that in a separate thread, so that it runs concurrently with your other code that waits for the user's input.

This is an example implementation of the above concept.

from threading import Thread
import time

def outputNumbers():
    for i in range(0,100000):
        time.sleep(1)
        print(i)

thread = Thread(target = outputNumbers)
thread.start()

input('Enter: ')
# Other code separate to counting thread here
Ryan Zhang
  • 1,856
  • 9
  • 19