0%

Python模拟鼠标键盘操作

安装PyUserInput前,需要安装如下依赖:

Linux - Xlib
Mac - Quartz, AppKit
Windows - pywin32, pyHook

1
pip install pywin32

https://www.lfd.uci.edu/~gohlke/pythonlibs/

安装pyHook,找到python对应的版本,比如:pyHook‑1.5.1‑cp37‑cp37m‑win_amd64.whl

下载到本地,安装

1
pip install pyHook‑1.5.1‑cp37‑cp37m‑win_amd64.whl

安装PyUserInput

1
pip install PyUserInput
1
2
3
4
5
from pymouse import PyMouse
from pykeyboard import PyKeyboard

m = PyMouse()
k = PyKeyboard()

调用api

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
x_dim, y_dim = m.screen_size()
m.click(x_dim/2, y_dim/2, 1)
k.type_string('Hello, 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


# 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')

eg.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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()