-1

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?

Wolf
  • 17
  • 4
  • 2
    What could possibly be the use for permanently updating a variable with the current time…? – deceze Sep 22 '22 at 15:20
  • the threading library should do this, the exact implementation depends on the code you are not showing, but in most practical cases i don't think you need to run 2 loops, as you can just read the time whenever you are reading the content of the `memory["time"]` variable. – Ahmed AEK Sep 22 '22 at 15:23
  • I refer you to https://stackoverflow.com/questions/73829765/how-to-run-2-functions-at-the-same-moment-python3-10#73829765 – DarkKnight Sep 23 '22 at 15:24

1 Answers1

0

"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()
JRose
  • 1,382
  • 2
  • 5
  • 18