I'm learning python for fun and what I'm trying to achieve here is a program that constantly asks user for input through a While True loop, while still running other scripts on background (Chosen by the user).
What I currently have works fine... But not exactly as I wanted. It takes the user's input and starts threads like asked, but pauses them while waiting for the user's next input. Then, it prints what my thread should print every second, but only once, after the console's next print.
I'm using IDLE to test my code regularly, maybe that could help.
Principal script:
from mythreadclass import MyThread
while True:
user_input = input("What do I do ? ")
if user_input == "start thread":
#Will start a threat that prints foo every second.
mythread = MyThread()
mythread.start()
elif user_input == "hello":
print("Hello !")
else:
print("This is not a correct command.")
Thread class:
import time
from threading import Thread, Timer
class MyThread(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
print("Thread started !")
while True:
self.foo()
time.sleep(1)
def foo(self):
print("foo !")
What I have when executing:
What do I do ?
>>> start thread
Thread started !
What do I do ?
>>> hello
foo !Hello !
>>> hello
foo !Hello !
As you can see, the thread should print foo! every second while still asking user for the next input. Instead, it starts the thread and prints foo ! only when the user types something: input pauses/blocks the thread.
I don't know if what I want to achieve is clear so here it is:
What do I do ?
>>> start thread
Thread started !
What do I do ?
foo !
foo !
foo !
#User waited 3 seconds before typing hello so there should be 3 foos
>>> hello
Hello !
What do I do ?
foo !
foo !
etc etc.
inputtoraw_inputand it all seems to work as expected. And I put everything in one file.