I want to run some function and print that the function is active at the time it runs, but only the function runs and the printing isn't. Why?
I'm using the threading
library in Python.
print("Waiting for key...")
keyboard_listening = Thread(target=key_pressed()) # key_pressed has while loop that
# prints every 1 second
info = Thread(target=print("After thread"))
keyboard_listening.start() # Running
info.start() # Not running
What is wrong?
You need to pass Thread
a callable, not the result of the function after you call it. This is the difference between key_pressed()
and key_pressed
.
So, you want something like
print("Waiting for key...")
keyboard_listening = Thread(target=key_pressed)
info = Thread(target=lambda: print("After thread"))
keyboard_listening.start()
info.start()
where lambda
is used to create a one-line function.