Python中的键盘按键输入
有没有办法让系统觉得某个键被按下了?比如说,我需要让 A 键被按下成千上万次,手动去做太耗时间了,我想写点东西来帮我完成这个任务,而我最熟悉的就是Python。
换句话说,我需要模拟一个按键的操作,而不是去捕捉一个按键的操作。
更多信息(应要求提供):我在使用Windows XP,需要把这些按键发送到另一个应用程序。
11 个回答
12
看看这个模块 keyboard,它有很多功能。你可以用这个命令来安装它:
pip3 install keyboard
然后使用这个代码:
import keyboard
keyboard.write('A',delay=0)
如果你想多次输入'A',那么只需要用一个循环就可以了。
注意:
按下的'A'键会在整个窗口中生效。这意味着即使你在运行这个脚本的时候去浏览器,脚本也会开始在那里输入内容。
46
你也可以使用PyAutoGui来发送虚拟按键。
这里是它的说明文档:https://pyautogui.readthedocs.org/en/latest/
import pyautogui
pyautogui.press('Any key combination')
你还可以发送像Shift键或Enter键这样的按键:
import pyautogui
pyautogui.press('shift')
PyAutoGui也可以直接发送文本,像这样:
import pyautogui
pyautogui.typewrite('any text you want to type')
如果你想按“A”键1000次,代码大概是这样的:
import pyautogui
for i in range(999):
pyautogui.press("a")
对于像alt-tab这样的操作,或者其他需要同时按下多个键的任务:
import pyautogui
# Holds down the alt key
pyautogui.keyDown("alt")
# Presses the tab key once
pyautogui.press("tab")
# Lets go of the alt key
pyautogui.keyUp("alt")
49
首先,安装 pywin32 这个扩展包。安装好之后,你就可以做以下操作:
import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want
接下来,查找 WScript.Shell 对象的相关文档(我记得在所有 Windows XP 的安装中,这个对象都是默认安装的)。你可以从 这里 开始找找看。
补充: 发送 F11
import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")
# Google Chrome window title
wsh.AppActivate("icanhazip.com")
wsh.SendKeys("{F11}")