Подпроцесс плохо взаимодействует с Pynput при создании горячих клавиш - PullRequest
1 голос
/ 02 апреля 2020

Я использую Pynput и Subprocess с NirCmd , чтобы создать HotKey, который выключит мой монитор. Программа работает нормально при первом запуске функции. Однако при повторном запуске функции нажатие любой клавиши ctrl вообще, даже самой, вызовет функцию. Это мой код:

import subprocess
from string import ascii_lowercase, digits
from pynput.keyboard import Key, KeyCode, Listener

#Function mapped to HotKey
def monitor_off():
    subprocess.run("ECHO Testing", shell=True) #<--- This is an example operation to show that the program works when doing anything other than running NirCmd
    #subprocess.run("nircmd monitor off", shell=True) '''<--- This is the problematic operation'''

#Combination to trigger the function monitor_off
combination_to_function = {
frozenset([Key.ctrl_l, Key.ctrl_r]): monitor_off,
}

#Creating set to store the keys being actively pressed
current_keys = set()

'''When a key is pressed, add it to the current_keys set.
Then check if the current_keys set matches any of the hotkey combinations.
If it does, execute the function mapped to the combination(s)'''
def on_press(key):
    current_keys.add(key)
    if frozenset(current_keys) in combination_to_function:
        combination_to_function[frozenset(current_keys)]()

#When a key is released, remove it from the current_keys set
def on_release(key):
    current_keys.remove(key)

#Joining on_press and on_release to the main thread
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
...