Is there a way to mimic the effect of the time.sleep() function without pausing the entire program?

Viewed 106

I am a new python 3.9 user who's trying to step up my coding. I'm writing a program that uses a while loop and will call functions to press keys based on user input. My code basically looks like:

from pynput.keyboard import Key, Controller
from graphics import *
import time
    
def wack():
   M = Controller()
   for i in range(3):
      M.press('a')
      time.sleep(1)    # This guy right here is the issue
      M.release('a')

def main():
    click = Win.checkMouse()
    while not click(click, exit_box):
       click = Win.checkMouse()
       if *input* == *correct string*:
          wack()
       

I have a graphics window with an exit button and when exit is clicked, it terminates the program and closes the window. The issue is that the time.sleep(1) doesn't pause the inputs or that point in the code, it pauses the entire program suspending the while loop which is not what I want it to do.

Searching about the time function hasn't provided any clear solutions since time.sleep() seems to be the most popular pausing function in python.

1 Answers

asyncio is an amazing feature added in python3.7 which allows you to wait for an object or function(callled a coroutine in the context of asynchronous python) to get a result while the rest of the program executes.

asyncio has a sleep method which paused only the asynchronous function(coroutine) and lets the rest of the code in the program execute

This is how:

from pynput.keyboard import Key, Controller
from graphics import *
import time
import asyncio

#This is the asnychronous funtion    
async def wack():
   M = Controller()
   for i in range(3):
      M.press('a')
      await asyncio.sleep(1)#this sleeps the function but allows the rest of the program to work
      M.release('a')

def main():
    click = Win.checkMouse()
    while not click(click, exit_box):
       click = Win.checkMouse()
       if *input* == *correct string*:
          asyncio.run(wack()) #calling the asynchronous funtion
       

Here is a tutorial on understanding asyn io for python

Related