python中库pynput的用法
时间: 2023-10-27 16:07:09 浏览: 151
pynput是一个Python库,用于控制和监视输入设备,如鼠标和键盘。以下是一些pynput库的用法示例:
1. 监视键盘输入:
```python
from pynput import keyboard
def on_press(key):
try:
print('Key {} pressed.'.format(key.char))
except AttributeError:
print('Key {} pressed.'.format(key))
def on_release(key):
print('Key {} released.'.format(key))
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
```
2. 控制鼠标移动:
```python
from pynput.mouse import Controller
mouse = Controller()
# Move the mouse relative to its current position
mouse.move(5, -5)
```
3. 监视鼠标输入:
```python
from pynput import mouse
def on_move(x, y):
print('Pointer moved to {0}'.format((x, y)))
def on_click(x, y, button, pressed):
if pressed:
print('Mouse clicked at ({0}, {1}) with {2}'.format(x, y, button))
def on_scroll(x, y, dx, dy):
print('Mouse scrolled at ({0}, {1})({2}, {3})'.format(x, y, dx, dy))
with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
```
这些仅仅是pynput库的一些用法,还有其他的功能,如控制键盘输入、控制鼠标点击等等。
阅读全文