简体   繁体   中英

I want to run 2 for loops concurrently, is it possible?

there are 2 loops i want to run, loop_1 and loop_2 i want to run them concurrently but its not working it run only 1 loop

# i've tried this one
import pyautogui
import time
import loop_1

pyautogui.FAILSAFE = True
times = interval=input("Enter speed: ")
text = input("Enter Text you want to repeat: ")
loops = int(input("Amount of repeats: "))

time.sleep(5)

for x in range(loops):
    pyautogui.press('enter', interval=0.01)
    pyautogui.typewrite(text, times)
    pyautogui.press('enter')
    pyautogui.typewrite(text, times)
    pyautogui.press('enter')

# loop_1

for i in range(100):
        pyautogui.press('enter', interval=0.01)

# loop_2

for x in range(loops):
    pyautogui.press('enter', interval=0.01)
    pyautogui.typewrite(text, times)
    pyautogui.press('enter')
    pyautogui.typewrite(text, times)
    pyautogui.press('enter')

its not working it just stuck in loop_1, i want it to run both the loops at the same time

Use multi-threading to run loops at the same time. Search for the keyword and you will find lots of tutorials about it. For example :

#import threading

'''
your code
'''
# loop_1
def loop1():
    for i in range(100):
        pyautogui.press('enter', interval=0.01)

# loop_2
def loop2(loops):
    for x in range(loops):
        pyautogui.press('enter', interval=0.01)
        pyautogui.typewrite(text, times)
        pyautogui.press('enter')
        pyautogui.typewrite(text, times)
        pyautogui.press('enter')

# Create two threads as follows
# target = executed function, args = parameter to be passed
t1 = threading.Thread(target=loop1, args=()) 
t2 = threading.Thread(target=loop2, args=(loops,)) 

# starting thread 1 
t1.start() 
# starting thread 2 
t2.start() 

# Now loop1 and loop2 are keep being executed

# Use join() to stop execution of current program until both loops are complete
# wait until thread 1 is completely executed 
t1.join() 
# wait until thread 2 is completely executed 
t2.join() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM