Python:同时执行规则间隔的多个循环(在Python中转换AutoHot键脚本)



我使用Python使键盘键同时打开/关闭多个循环,每个循环每[1-5s]独立执行一次。基本上,我想在Python中复制AutoHotkey脚本。

循环开始后,我需要pynput代码来继续监听按键,并能够启动/停止任何循环。我遇到的问题之一是如何使用asyncio从AHK复制settimer函数(settimer函数会使函数在指定的时间间隔内自动重复调用。您可以在它运行时执行其他操作(。

我当前的Python代码

import pyautogui,time
import random
from random import randint
import time
from time import sleep
from pynput import keyboard
from pynput.keyboard import Key, Listener
import threading
from datetime import datetime 
import asyncio
toggle1 = False

def start_loop1():
start_time = time.time()
async def stuff():
await asyncio.sleep(random.random() * 3)
print(round(time.time() - start_time, 1), "Finished doing stuff")
async def do_stuff_periodically(interval, periodic_function):
while True:
print(round(time.time() - start_time, 1), "Starting periodic function")
await asyncio.gather(
asyncio.sleep(interval),
periodic_function(),
)
global toggle1
print("toggle1 STATE:", toggle1)
toggle1 = not toggle1
if toggle1== False:
task.cancel()
task= asyncio.run(do_stuff_periodically(5, stuff))


def on_press(key):
#    print('{0} pressed'.format(key)) 
if key.char in ("a"):
global toggle1
toggle1 = not toggle1
print("toggle1 STATE:", toggle1)
if toggle1:
start_loop1()

return False

def on_release(key):
print('{0} release'.format(key))
if key == Key.esc:
# Stop listener
return False

# Collect events until released
with Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()

aHK代码我正在尝试复制

Random(Min := "", Max := "")
{
Random Out, % Min, % Max
return out
}
Toggle := 0
*a::
Toggle := !Toggle
if Toggle 
{
send {a down}
settimer, Loop1, 10130, on
settimer, Loop2, 6185, on
sleep,% Random(30,60 )
send {q}
sleep,% Random(30,60 )
send {r}
} else {
settimer, Loop1, off
settimer, Loop2, off
send {a up}
}
return
Loop1: 
send {q}
SetTimer, Loop1,off
SetTimer, Loop1, % Random(10200,10230 ),on  
return
Loop2: 
send {r}
SetTimer, Loop2,off
SetTimer, Loop2, % Random(6220,6245 ),on
return

单向,使用keyboard模块。

import time
import threading
import logging
from queue import Queue
import keyboard
def do_something():
... # do whatever

class StopMessage:
...
LOOP1_QUEUE = Queue() # queue to contain stop messages
def loop1():
while True:
if not LOOP1_QUEUE.empty():
t = LOOP1_QUEUE.get()
assert t is StopMessage, 'unexpected queue contents'
LOOP1_QUEUE.task_done()
break # stop the loop
do_something() # otherwise keep doing things
time.sleep(0.1)
LOOP2_QUEUE = Queue()
def loop2():
...
# basically the same as loop1, but with a different queue
# maybe different ``do_something``, wait times, or whatever
# this can be generalized, if you want.

queues = [LOOP1_QUEUE, LOOP2_QUEUE]
threads = []
startstop_lock = threading.Lock()

def start_loops():
assert not threads, 'must stop loops before they can be started'
t1 = threading.Thread(target=loop1)
t2 = threading.Thread(target=loop2)
t1.start(); t2.start()
threads = [t1, t2]
def stop_loops():
assert threads, 'threads must be started in order to be stopped'
for q in queues:
q.put(StopMessage)
for q in queues:
q.join()
while threads:
t = threads.pop()
t.join()
def is_running():
return bool(threads)
def startstop():
with startstop_lock:
if not is_running():
start_loops()
else:
stop_loops()
keyboard.add_hotkey('ctrl+shift+a', startstop)
def main():
while True:
time.sleep(1)  
# can do other things in the main thread
# while everything else happens in the background.
# or just do nothing
if __name__ == '__main__':
main()

这是您提供的AHK代码的粗略近似值。

最新更新