0

I'm new to async funcs in Python, so excuse me if I look newbie at it.

I've got a program which runs inside an infinite loop for automating a task. I would like to know how could I make an async function that modifies a global variable when I press, for example, the K letter.

An example would be enough so I can complete the other tasks I have. I didn't try anything because I don't know how to start for async. Using Python 3.9.

Hope someone can answer so it can also help others, didn't find anything in my search.

Thanks in advance.

while True:

   ConsoleLog("NEWLINE", "")

   if(putHerosToWork == False and preventAFK == False):
       ConsoleLog("BLANK", "")
       CheckConnection()

   if(isClientConnected == True):
       CheckNewMapEvent()
       CheckTimeEvents()

       # Put Heros to Work
       if(putHerosToWork == True):
           doPutHerosToWork()

       # Prevent AFK
       if(preventAFK == True):
           doPreventAFK()
        
   time.sleep(10)
   cls()
  • BTW, in case it matters, using Python in Linux. – Iván S. Rodríguez Nov 13 '21 at 23:16
  • Should be no problem modifying a global variable in an async function. Do you have an example of your code that listens for the key press? – Iain Shelvington Nov 13 '21 at 23:59
  • Hello Iain, thanks for answering. I don't know how to make the listener. Added an example of the loop. The variables I want to edit on async keypress are putHerosToWork and preventAFK. Thanks in advance. – Iván S. Rodríguez Nov 14 '21 at 00:09
  • 1
    So you're really asking "how to detect a keypress"? https://stackoverflow.com/questions/24072790/how-to-detect-key-presses – Grismar Nov 14 '21 at 00:16
  • Hello Grismar. Thanks for answering. Yes and no. That link you sent me doesn't tell me how to do it by async, as in the implementation you send I would have to keep the key pressed until that piece of code is executed (notice the loop), and that's what I don't want. I need it to be async, to have a "listener" that modifies the variable in the exact moment I press the key. – Iván S. Rodríguez Nov 15 '21 at 08:26

1 Answers1

0

I got the answer by doing threads, async was not correct in this case.

Here is the code I used.

def detectKeyPress():
   global putHerosToWork

   while True:
       if keyboard.is_pressed('q'):
           print("press")
           time.sleep(1)
           putHerosToWork=True
           time.sleep(1)
    

p1 = Process(target=detectKeyPress)
p1.start()
General Grievance
  • 4,555
  • 31
  • 31
  • 45