1

I am writing a program in python that requires the program to constantly run in the background with the option of the user typing at any time to pause the program or end it.

So far I can only get the program to completely stop and wait for the user to enter something.

uInput = ""

counter = 3

while uInput != "password" and counter >= 0:
    uInput = input

    if uInput != "password":
        print("Incorrect Password.", counter, "tries remaining.")
        counter -= 1

The input statement completely freezes the program until the user presses enter. Is it possible to have the program run for example a timer or just another program in general while it waits for the user to input something? Any tutorials or tips will be helpful.

ChristopherOjo
  • 237
  • 1
  • 12

1 Answers1

0

Use the time module and threading module for this. Code:

from threading import Thread
import time

uInput = ""

counter = 3

thread_running = True


def passwordInputting():
    global counter
    start_time = time.time()
    while time.time() - start_time <= 10:
        uInput = input()
        if uInput != "password":
            print("Incorrect Password.", counter, "tries remaining.")
            counter -= 1
                                
        else:
            # code for if password is correct
            break

def passwordTimer():

    global thread_running
    global counter

    start_time = time.time()

    # run this while there is no input or user is inputting
    while thread_running:
        time.sleep(0.1)
        if time.time() - start_time >= 10:
            if uInput == "password":
                continue
            else:
                if counter > 0:
                    print("Incorrect Password.", counter, "tries remaining.")
                    counter -= 1
                    start_time = time.time() + 10
                    
                else:
                    # code for when no more tries left
                    break
                
timerThread = Thread(target=passwordTimer)
inputThread = Thread(target=passwordInputting)

timerThread.start()
inputThread.start()

inputThread.join() # interpreter will wait until your process get completed or terminated
thread_running = False

If you want to learn more about threading yourself, look here: https://realpython.com/intro-to-python-threading/

Timo
  • 46
  • 7