by James
by James

Reputation: 99

Having 2 seperate infinite Loops

I want to recieve the keypresses of the User using msvcrt.getch, while I also want the program to write something to the screen every second. Thats my code:

while True:
    key = getch()        

    print("one second")
    sleep(1)

When I run it, it only continues writing one second to the screen when I press something.

Upvotes: 0

Views: 34

Answers (2)

skymon
skymon

Reputation: 870

You could use Threading, e.g. like this:

import threading
import time

def input_action():
    while True:
        key = getch()

def print_action():
    while True:
        print("one second")
        time.sleep(1)

if __name__ == "__main__":
    input_thread = threading.Thread(target=input_action)
    print_thread = threading.Thread(target=print_action)
    input_thread.start()
    print_thread.start()

Upvotes: 2

Chris Charles
Chris Charles

Reputation: 4446

msvcrt also has a method called kbhit which is true if there is a char waiting to be read. So you can call that before reading the char.

while True:
    if kbhit():
        key = getch()

    print("one second")
    sleep(1)

Upvotes: 1

Related Questions