Search code examples
pythonpython-3.xpynput

How to press media keys using pynput in windows?


I need to pres the play media key but i can't find the aproppiate key value

I've tried doing

from pynput.keyboard import Key, Controller
keyboard= Controller()
keyboard.press(Key.MediaPlayPause)
keyboard.release(Key.MediaPlayPause)

But it won't work I don't get any error

Error traceback

Traceback (most recent call last):
  File "2.py", line 63, in <module>
    keyboard.press(Key.MediaPlayPause)
  File "C:\Users\nebbu\AppData\Local\Programs\Python\Python37\lib\enum.py", line 349, in __getattr__
    raise AttributeError(name) from None
AttributeError: MediaPlayPause

Solution

  • UPDATE:

    Since pynput version 1.5.0 media keys are available for use. The available keys are described here: (https://pynput.readthedocs.io/en/latest/keyboard.html#pynput.keyboard.Key.media_next)


    Media control still not available on pynput. (https://github.com/moses-palmer/pynput/pull/171)

    You can emit a key input event by using a virtual-key code:

    from pynput.keyboard import Controller, KeyCode
    
    
    def main():
        keyboard = Controller()
    
        print('Pausing/Resuming... ')
    
        keyboard.press(KeyCode.from_vk(0xB3))  # Play/Pause
    
    if __name__ == "__main__":
        main()
    

    In the sample we are using Play/Pause virtual key code (0xB3). You can check the full list of possible values here https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes