Python 创建热键时,子进程与Pynput接口不好

Python 创建热键时,子进程与Pynput接口不好,python,subprocess,pynput,nircmd,Python,Subprocess,Pynput,Nircmd,我正在使用Pynput和Subprocess with创建一个热键,它将关闭监视器。第一次触发该功能时,程序工作正常。但是,当第二次触发该功能时,按下任何ctrl键(即使是单独按下)都会触发该功能。 这是我的代码: import subprocess from string import ascii_lowercase, digits from pynput.keyboard import Key, KeyCode, Listener #Function mapped to HotKey de

我正在使用Pynput和Subprocess with创建一个热键,它将关闭监视器。第一次触发该功能时,程序工作正常。但是,当第二次触发该功能时,按下任何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()
导入子流程
从字符串导入ascii_小写数字
从pynput.keyboard导入键、键代码、侦听器
#映射到热键的函数
def监视器_关闭():

subprocess.run(“ECHO Testing”,shell=True)#在我的计算机中,只有当我同时按下两个ctrl按钮时,它才会打印
测试
。如果我只按下一个按钮,它就不会打印
测试
。这是一个示例操作,向您显示程序在执行除调用NirCmd以外的任何操作时都能正常工作。我知道,.你的问题是,当第二次触发该函数时,按任何ctrl键都会触发该函数,即使按ctrl键本身也是如此..但在我的计算机中工作正常。你是否将其与NirCmd一起使用?我的意思是,问题出在NirCmd和子进程之间的交互中,但我不知道问题出在哪里。在我的计算机中,只有当我同时按下两个ctrl按钮时,它才会打印测试。如果我只按下一个按钮,它就不会打印测试。这是一个示例操作,为了向您展示该程序在执行除调用NirCmd以外的任何操作时都能正常工作。我知道。您的问题是,在第二次触发该函数时,按任何ctrl键都会触发该函数,即使按ctrl键本身也会触发该函数。但它在我的计算机中运行良好。您是否将其与NirCmd一起使用?我想说的是,问题在于NirCmd和子流程之间的交互,但我不知道这是什么问题。