python自動化滑鼠和鍵盤PyUserInput(pymouse和pykeyboard)
引
在使用電腦的時候,偶爾有需求要模擬滑鼠鍵盤,進行一些機械重複的操作(重新整理網頁、搶票、某些小遊戲等)。如果為此專門下載一個按鍵精靈,總感覺殺雞用牛刀,所以就開始探索一些輕量級解決方案。本人電腦上配置了Python,自然就想到那句名言
方案
參考網上的各種例子後,發現了PyUserInput這個專案。在配置完成後,呼叫非常簡便。
準備
進入專案主頁,可以看到這個Python庫是跨平臺支援的,但是對應不同平臺,需要安裝依賴庫。
Linux - Xlib (python-xlib)
Mac - Quartz, AppKit
Windows - pywin32, pyHook
安裝
使用pip工具,直接安裝
pip install PyUserInput
呼叫方法
以下部分參考PyUserInput專案在Python官網的說明只做簡要翻譯,方便理解。詳細方法可以呼叫help()函式檢視。
在安裝完PyUserInput後,pymouse和pykeyboard模組就被安裝到你的Python路徑下。
建立一個滑鼠和鍵盤物件:
from pymouse import PyMouse
from pykeyboard import PyKeyboard
m = PyMouse()
k = PyKeyboard()
接下來是一個示例,完成點選螢幕中央並鍵入“Hello, World!”的功能:
x_dim, y_dim = m.screen_size()
m.click(x_dim/2, y_dim/2, 1)
k.type_string('Hello, World!')
PyKeyboard還有很多種方式來發送鍵盤鍵入:
# pressing a key k.press_key('H') # which you then follow with a release of the key k.release_key('H') # or you can 'tap' a key which does both k.tap_key('e') # note that that tap_key does support a way of repeating keystrokes with a interval time between each k.tap_key('l',n=2,interval=5) # and you can send a string if needed too k.type_string('o World!')
並且它還支援很多特殊按鍵:
# pressing a key
k.press_key('H')
# which you then follow with a release of the key
k.release_key('H')
# or you can 'tap' a key which does both
k.tap_key('e')
# note that that tap_key does support a way of repeating keystrokes with a interval time between each
k.tap_key('l',n=2,interval=5)
# and you can send a string if needed too
k.type_string('o World!')
並且它還支援很多特殊按鍵:
#Create an Alt+Tab combo
k.press_key(k.alt_key)
k.tap_key(k.tab_key)
k.release_key(k.alt_key)
k.tap_key(k.function_keys[5]) # Tap F5
k.tap_key(k.numpad_keys['Home']) # Tap 'Home' on the numpad
k.tap_key(k.numpad_keys[5], n=3) # Tap 5 on the numpad, thrice
注意,你也可以使用press_keys方法將多個鍵一起傳送(例如,使用某些組合鍵):
# Mac example
k.press_keys(['Command','shift','3'])
# Windows example
k.press_keys([k.windows_l_key,'d'])
平臺之間的一致性是一個很大的挑戰,請參考你使用的作業系統對應的原始碼,來理解你需要使用的按鍵格式。例如:
# Windows
k.tap_key(k.alt_key)
# Mac
k.tap_key('Alternate')
我還想特別說明一下PyMouseEvent和PyKeyboardEvent的使用。
這些物件是一個架構用於監聽滑鼠和鍵盤的輸入;他們除了監聽之外不會做任何事,除非你繼承他們【注1】。PyKeyboardEvent為編寫完成,所以這裡是一個繼承PyMouseEvent的例子:
from pymouse import PyMouseEvent
def fibo():
a = 0
yield a
b = 1
yield b
while True:
a, b = b, a+b
yield b
class Clickonacci(PyMouseEvent):
def __init__(self):
PyMouseEvent.__init__(self)
self.fibo = fibo()
def click(self, x, y, button, press):
'''Print Fibonacci numbers when the left click is pressed.'''
if button == 1:
if press:
print self.fibo.next()
else: # Exit if any other mouse button used
self.stop()
C = Clickonacci()
C.run()