使用 while 循环执行 2 个异步任务

Executing 2 async tasks with while loop

我尝试在光标移动时点击特定区域, task_0 得到执行,打印也能正常工作,但其他任务没有得到执行。 我试过使用 ensure_future ,代码没有错误。

import pyautogui
import time
import asyncio


async def main():
    print(pyautogui.size())
    task_0 = asyncio.create_task(cursor_track())
    print("before minimize...")
    task_1 = asyncio.create_task(minimize_click())
    task_2 = asyncio.create_task(will_it_run())
    


async def will_it_run():
    print("running!...")


# Click on minimize
async def minimize_click():
    print("\nTest...\n")
    x, y = pyautogui.position()

    while True:
        if (1780 <= x <= 1820) and (0 <= y <= 25):
            pyautogui.click(clicks=1)


# Prints Cursor position
async def cursor_track():
    print('Press Ctrl-C to quit.')
    try:
        while True:
            x, y = pyautogui.position()
            positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
            print(positionStr, end='')
            time.sleep(0.1)
            print('\b' * len(positionStr), end='', flush=True)
    except KeyboardInterrupt:
        print('\n')


asyncio.run(main())

print("async test finished...")

我使用 await asyncio.sleep 来确保函数为另一个函数提供时间 运行 问题不是使用 await

import pyautogui
import time
import asyncio


async def track_and_minimze():
    print("\n"+str(pyautogui.size())+"\n")

    task_0 = asyncio.create_task(cursor_track())
    task_1 = asyncio.create_task(minimize_click())

    await task_0
    await task_1

# Click on minimize
async def minimize_click():
   
    while True:
        x, y = pyautogui.position()
        await asyncio.sleep(0.01)
        if (1780 <= x <= 1825) and (0 <= y <= 25):
            pyautogui.click(clicks=1)

# Prints Cursor position
async def cursor_track():

    try:
        while True:
            x, y = pyautogui.position()
            positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
            await asyncio.sleep(0.01)
            print(positionStr, end='')
            time.sleep(0.05)
            print('\b' * len(positionStr), end='', flush=True)