如何创建在后台运行并对键盘输入作出反应的Python脚本?
目前,我正在使用通过键盘快捷键触发脚本。比起处理自动热键,我更喜欢用Python编程。每当我接触自动热键脚本时,我希望我能简单地编写干净的自动热键代码 让我们看一下简单的自动热键脚本,当我按下insert键时,它会在我所在的任何窗口中打印如何创建在后台运行并对键盘输入作出反应的Python脚本?,python,windows,python-3.x,background-process,Python,Windows,Python 3.x,Background Process,目前,我正在使用通过键盘快捷键触发脚本。比起处理自动热键,我更喜欢用Python编程。每当我接触自动热键脚本时,我希望我能简单地编写干净的自动热键代码 让我们看一下简单的自动热键脚本,当我按下insert键时,它会在我所在的任何窗口中打印hello world: foo(){ send, "hello world" } Insert:: foo() 如何在Windows上的Python3中执行相同的操作?您可以结合StackOverflow的两个答案来(几乎)解决这个问题 使用answ
hello world
:
foo(){
send, "hello world"
}
Insert:: foo()
如何在Windows上的Python3中执行相同的操作?您可以结合StackOverflow的两个答案来(几乎)解决这个问题
getch()
的方法,从用户那里读入一个字符,而不需要\n
。(答案重复如下)\u Getch()
类# This code is a combination of two StackOverflow answers
# (links given in the answer)
# ------- Answer 1 by tehvan -----------------------------------
class _Getch:
"""Gets a single character from standard input.
Does not echo to the screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _GetchUnix:
def __init__(self):
import tty, sys
def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
class _GetchWindows:
def __init__(self):
import msvcrt
def __call__(self):
import msvcrt
return msvcrt.getch()
getch = _Getch()
# -------- Answer 2 by Barafu Albino (modified) -------
import _thread
def input_thread(a_list):
_Getch().__call__()
a_list.append(True)
def do_stuff():
a_list = []
_thread.start_new_thread(input_thread, (a_list,))
print('Press any key to stop.')
while not a_list:
pass
# This is where you can put the stuff
# you want to do until the key is pressed
print('Stopped.')
do_stuff()
要实现这一点,你必须把它挂在窗户上。您可能必须通过
ctypes
或模块来实现这一点,因为中似乎不存在必要的API
根据,您将需要使用三个windows API调用:
- ,使用
WH\u键盘LL设置键盘挂钩;查看键盘事件的函数idHook
- 最终取下钩子
- 如果你对某个按键不感兴趣,把它传给下一个钩子