简体   繁体   English

我想同时运行 2 个 for 循环,这可能吗?

[英]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我想运行 2 个循环,loop_1 和 loop_2 我想同时运行它们但它不起作用它只运行 1 个循环

# 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它不工作它只是卡在 loop_1 中,我希望它同时运行两个循环

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() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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