0

suppose there is this code

import time

function():
 print("abcd")
 time.sleep(1)
 print("efgh")

function()

I want the function() to run whenever I press a combination of keys from anywhere on the pc. Like, suppose I am on chrome watching a youtube video, and I press suppose shift+alt+b then the function() should start running and print those things.

I am on windows 10 working on python 3.8 I guess.

Chinar
  • 7
  • 4
  • You can check this [page](https://nitratine.net/blog/post/how-to-detect-key-presses-in-python/) – Onur Dec 22 '20 at 07:49
  • Use a library like [pynput](https://pypi.org/project/pynput/) or directly interact with the api of your OS. In windows it's the [win32api](https://pypi.org/project/pywin32/), on linux you can read from `/dev/input`. – Countour-Integral Dec 22 '20 at 07:57
  • I am not able to understand. can you make the code and answer the question. – Chinar Dec 22 '20 at 09:00

1 Answers1

0

I've figured it out on my own. It turns out that using the keyboard module is much simpler than using pynput.

Here is the code for your reference:

import keyboard 
import time

def function():
   print("abcd")
   time.sleep(1)
   print("efgh")

while True: # Infinite loop to keep the program running
    try:
        if keyboard.is_pressed('shift'): 
            if keyboard.is_pressed('alt'):
                if keyboard.is_pressed('b'):
                    function()
    except:
        pass  

Andreas Violaris
  • 2,465
  • 5
  • 13
  • 26
Chinar
  • 7
  • 4