I've recently started programming and I'm a little stuck on this program i'm trying to write.
essentially I need 2 while True loops playing at once but for some reason it plays the first loop once and then goes straight to the second. Heres my code:
import keyboard
import time
while True:
keyboard.write("t")
time.sleep(0.25)
while True:
keyboard.write("s")
keyboard.write("e")
time.sleep(0.50)
So it's meant to press the 'T' Key every 0.25 seconds and the 'S E' keys every 0.5 seconds all at the same time.
I've tried searching online for examples of similar programs that use loops and keyboards but to no luck.
Any guidance would be really appreciated
CodePudding user response:
The second while
loop is infinite, thus infinity never ends, so how do you expect it to go back to the outer while loop, so I think you meant:
c = 0
while True:
keyboard.write("t")
time.sleep(0.25)
c = 1
if not c % 2:
keyboard.write("s")
keyboard.write("e")
Your code only would work if you're Chunk Norris :) He can count to infinity twice :P
CodePudding user response:
It sounds like you think that different sections of code just run simultaneously without reference to each other. Unfortunately python is an imperative language, so each line executes before going on to the next.
You may have to collapse the loops into one and execute the se
every other loop:
import keyboard
import time
import itertools
for se in itertools.cycle((False, True)):
keyboard.write("t")
time.sleep(0.25)
if se:
keyboard.write("s")
keyboard.write("e")
CodePudding user response:
Update:
I've added the following:
from multiprocessing import Process
if __name__ == '__main__':
Process(target=t).start()
Process(target=se).start()
This seems to have solved my issue