我正在编写一个脚本,当用户按下Shift + P时将输入文本字符串。它可以工作,当我按Shift + P时,它可以输入文本,但不会停止输入文本。我认为这是我做过的事情,现在还没有看到。为什么这会不断循环和键入,如何在一次键入“ Hello,World”后停止它?
from pynput import keyboard
import pyautogui as pg
COMBINATIONS = [
{keyboard.Key.shift, keyboard.KeyCode(char="p")},
{keyboard.Key.shift, keyboard.KeyCode(char="P")}
]
current = set()
def execute():
pg.press("backspace")
pg.typewrite("Hello, World\n", 0.25)
def on_press(key):
if any ([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
execute()
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
答案 0 :(得分:1)
这里发生的事情很棘手。 py.typewrite调用on_press信号处理程序。但这不只是调用它,而是用keyboard.Key.Shift调用on_press,因为Hello World中的大写字母H(shift-h)和感叹号(shift-1)!
首先,您可以看到发送hello world
而不发送Hello World!
的区别。对于小写版本,打字机从不发送shift键,因此我们不运行on_press且它不发送没想到,哦,我们有p并向下移动,完成后我们需要再次运行Hello World。
一种解决方案是制作一个全局process_keystrokes,并在运行execute()时将其关闭。清除键集似乎也是一个好主意,因为我们不知道打字机发送键击时用户可以/可能做些什么。
from pynput import keyboard
import pyautogui as pg
COMBINATIONS = [
{keyboard.Key.shift, keyboard.KeyCode(char="p")},
{keyboard.Key.shift, keyboard.KeyCode(char="P")}
]
current = set()
pg.FAILSAFE = True # it is by default, but just to note we can go to the very upper left to stop the code
process_keystrokes = True
def execute():
global process_keystrokes
process_keystrokes = False # set process_keystrokes to false while saying HELLO WORLD
pg.press("backspace")
pg.typewrite("#Hello, World\n", 1)
process_keystrokes = True
def on_press(key):
if not process_keystrokes: return
if any ([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
print("Added", key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
execute()
current.clear() # note this may potentially not track if we held the shift key down and hit P again. But unfortunately typewriter can stomp all over the SHIFT, and I don't know what to do. There seems to be no way to tell if the user let go of the shift key, so it seems safest to clear all possible keystrokes.
def on_release(key):
if not process_keystrokes: return
if any([key in COMBO for COMBO in COMBINATIONS]):
print("Removed", key)
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()