当前位置:   article > 正文

Python的pynput模块使用

pynput


前言

最近用到这个模块 边学边用, 写个小结,很多地方可能写的不对 用词不当


一、pynput是什么?

官方说法:“他可以控制和监听我们的输入设备,目前支持鼠标和键盘的控制与监听;因为我只使用了设备的控制 至于监听并没作深入了解 文章也不设计”

二、使用步骤

1.安装pynput模块

很简答:

pip install pynput
#使用ctrl+v 快捷粘贴时候用到
pip install pyperclip
  • 1
  • 2
  • 3

2.键盘控制

如下:

from pynput.keyboard import Key, Controller as c_keyboard
from pynput.mouse import Button, Controller as c_mouse

keyboard = c_keyboard()
#字符与数字
keyboard.press('a')
keyboard.release('a')

keyboard.press('A')
keyboard.release('A')

keyboard.press('1')
keyboard.release('1')
#非数字与字母键 详情: https://pynput.readthedocs.io/en/latest/keyboard.html#pynput.keyboard.Key
keyboard.press(Key.enter);
keyboard.release(Key.enter);
#组合
##全选
keyboard.press(Key.ctrl)
keyboard.press('a')
time.sleep(2)
keyboard.release('a')
keyboard.release(Key.ctrl)
###或者
with keyboard .pressed(Key.ctrl):
 keyboard.press('a')
 keyboard.release('a')
##复制
seller_nick = 'www.baidu.com/a.php?a=a&b=2'
pyperclip.copy('https://'+seller_nick.replace('amp;',''))
##粘贴
keyboard.press(Key.ctrl)
keyboard.press('v')
time.sleep(1)
keyboard.release('v')
keyboard.release(Key.ctrl)
##回车
keyboard.press(Key.enter);
keyboard.release(Key.enter);
  • 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
  • 38
  • 39

2.鼠标控制

如下:

from pynput.keyboard import Key, Controller as c_keyboard
from pynput.mouse import Button, Controller as c_mouse

mouse= c_mouse()
#点击
##双击
mouse.click(Button.left, 2)
##按下右键
mouse.press(Button.right)
##释放右键
mouse.release(Button.right)
#鼠标坐标
print(mouse.position) 
##x轴坐标
print(mouse.position[0]) 
##y轴坐标
print(mouse.position[1])
#移动
##移动到绝对坐标
mouse.position = (400, 38)
##相对当前坐标移动
mouse.move(300, 2)
#滑动
mouse.press(Button.left)
mouse.move(300, 2)
mouse.release(Button.left)
  • 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

总结

用法还是非常多的 其他详细见官方文档吧 查看官方文档

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/839544
推荐阅读
相关标签
  

闽ICP备14008679号