pynput.keyboard 按键无响应时终止程序
pynput.keyboard terminate program when key is pressed not responding
我这里有这段代码,我想要的是每 5 秒输入一次“potato”的代码。我还想要一个“退出”命令,我想要它以便在我按下 =
时它会停止程序。然而,代码不仅不起作用,而且还在它后面键入“=” types/enters “potato”。有人可以帮忙吗?谢谢
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
time.sleep(3)
while True:
keyboard.type('potato')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
if keyboard.type('asdf'):
quit()
time.sleep(5)
P.S。没有错误或任何东西
这里最明显的答案是在 if
语句中将“asdf”更改为“=”,但如果这不能解决问题,您可以添加一个侦听器来检测按键。
from pynput import keyboard, Key, Controller
import time
# set your termination key here
cut_key = "="
# check if key pressed is cut_key, if so, quit
def on_press(key):
try:
if key.char == cut_key:
quit()
except AttributeError:
if key == cut_key:
quit()
# non-blocking listener
listener = keyboard.Listener(
on_press=on_press)
listener.start()
keyboard = Controller()
time.sleep(3)
while True:
keyboard.type('potato')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(5)
我没有测试这段代码,如果它不起作用请评论。
https://pynput.readthedocs.io/en/latest/keyboard.html
我这里有这段代码,我想要的是每 5 秒输入一次“potato”的代码。我还想要一个“退出”命令,我想要它以便在我按下 =
时它会停止程序。然而,代码不仅不起作用,而且还在它后面键入“=” types/enters “potato”。有人可以帮忙吗?谢谢
from pynput.keyboard import Key, Controller
import time
keyboard = Controller()
time.sleep(3)
while True:
keyboard.type('potato')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
if keyboard.type('asdf'):
quit()
time.sleep(5)
P.S。没有错误或任何东西
这里最明显的答案是在 if
语句中将“asdf”更改为“=”,但如果这不能解决问题,您可以添加一个侦听器来检测按键。
from pynput import keyboard, Key, Controller
import time
# set your termination key here
cut_key = "="
# check if key pressed is cut_key, if so, quit
def on_press(key):
try:
if key.char == cut_key:
quit()
except AttributeError:
if key == cut_key:
quit()
# non-blocking listener
listener = keyboard.Listener(
on_press=on_press)
listener.start()
keyboard = Controller()
time.sleep(3)
while True:
keyboard.type('potato')
keyboard.press(Key.enter)
keyboard.release(Key.enter)
time.sleep(5)
我没有测试这段代码,如果它不起作用请评论。 https://pynput.readthedocs.io/en/latest/keyboard.html