Run 2 while Trues at the same time Python

Viewed 38

I'm trying to show a prompt to the user with an infinite input (like a terminal), but at the same time I want to be updating the time variable.

I wrote the following code:

import datetime

memory = {
    "time" : datetime.datetime.now()
}

def update_time():
    while True:
        memory["time"] = datetime.datetime.now()

def code():
    while True:
        command = input("Z>").strip()
        commandl = command.lower()
        # here it's where the if conditions are

I know I coud use the datetime.datetime.now() itself in the code() function, but in my case I realy need to have a variable with it.

I also see other answers with a threading library, but none of these works with the input in code().

Does anyone know how to run the update_time() and the code() at the same time?

1 Answers

"But none of these works with the input in code()". Can you explain what about this simple multithreaded program does not work?

import datetime
from threading import Thread

memory = {
    "time" : datetime.datetime.now()
}

def update_time():
    while True:
        memory["time"] = datetime.datetime.now()

def code():
    Thread(target=update_time).start()
    while True:
        command = input("Z>").strip()
        commandl = command.lower()
        print(memory)
        # here it's where the if conditions are

code()
Related