Python中用pynput制作划词复制功能的代码是什么

Admin 2022-09-19 群英技术资讯 278 次浏览

今天就跟大家聊聊有关“Python中用pynput制作划词复制功能的代码是什么”的内容,可能很多人都不太了解,为了让大家认识和更进一步的了解,小编给大家总结了以下内容,希望这篇“Python中用pynput制作划词复制功能的代码是什么”文章能对大家有帮助。


Windows系统环境下Python脚本实现全局“划词复制”功能
from pynput import mouse
import time
import threading

__DEBUG = False

def log(msg,debug=False):
    if __DEBUG or debug:
        print(msg)

class MouseMonitor():
    __press_time = 0
    __press_double_state = False
    __move = (0,0)

    def __init__(self,on_selected=None):
        if on_selected:
            self.on_selected = on_selected
        else:
            self.on_selected = self.on_selected

        self.listener = mouse.Listener(on_move=self.on_move,on_click=self.on_click)
        self.listener.start()
        self.listener.join()

    def on_selected(msg):
        print('selected "%s" has been copied.' % (msg,))

    def on_move(self,x,y):
        if self.__press_time == 0:
            self.__move = (x,y)
        # log(self.__press_time,time.time())
        # log('Pointer moved to {0}'.format((x,y)))

    def on_click(self,x,y,button,pressed):
        if str(button) == 'Button.left':
            if pressed:
                self.on_pressed(x,y)
            else:
                self.on_released(x,y)

    def on_pressed(self,x,y):
        if self.__press_double_state:
            # double click
            # self.__press_double_state = False
            if not self.check_not_time_out(self.__press_time, time.time(),0.4): # miss double click
                log('double1 click timeout and reset then')
                self.reset()
                self.__press_time = time.time()
        else:
            # single click
            self.__press_time = time.time()
            # self.__press_double_state = False

    def on_released(self,x,y):
        if self.__press_double_state:
            # double click
            if self.check_not_time_out(self.__press_time, time.time(),0.8):
                log('double click: %s' % (self.get_copy()))
                self.on_selected(self.get_copy())
                self.__press_double_state = False
            else:
                log('double2 click timeout and reset then')
                self.reset()
        else:
            if self.check_not_time_out(self.__press_time, time.time()):
                log('double click maybe')
                self.__press_double_state = True
                threading.Timer(0.5, self.timeout_handler).start() # wait timeout to reset
            elif not self.check_not_time_out(self.__press_time, time.time(),1):
                if self.__move != (0,0):
                    self.on_selected(self.get_copy())
                    log('selected: %s' % (self.get_copy(),))
                    self.reset()
            else:
                log('reset state')
                self.reset()

    def get_copy(self):
        import win32clipboard as wc
        import win32con

        def trigger_copy():
            from pynput.keyboard import Key,Controller
            key = Controller()
            with key.pressed(Key.ctrl):
                key.press('c')
                key.release('c')
            time.sleep(0.1) # wait for ctrl+c valid

        trigger_copy()
        msg = ''
        try:
            wc.OpenClipboard()
            msg = wc.GetClipboardData(win32con.CF_UNICODETEXT)
            wc.CloseClipboard()
        except TypeError:
            log('Clipboard Content is TypeError.')
        return msg

    def reset(self):
        self.__press_time = 0
        self.__press_double_state = False
        self.__move = (0,0)

    def timeout_handler(self):
        self.reset()
        log('timeout reset state')

    def check_not_time_out(self,old,new,delta=0.2):
        if(new - old > delta): # time delta > 0.2s
            return False
        else:
            return True


def printf(msg):
    log('copy content:'+msg,True)
    # log('x = {0} , y = {1}'.format(x,y))


if __name__ == '__main__':
    mm = MouseMonitor(printf)

pynput库的官方文档

实现代码

参考的博客实现了划词复制,但是看了下他的代码写的有点复制混乱,监听准确率并不高且不太容易理解。

实际监听鼠标的划词操作逻辑很简单:

记录下鼠标左键按下时的位置,当鼠标左键松开时,记录下鼠标左键松开的位置,如果按下的位置和松开的位置不一致,说明鼠标正在划词。

from pynput.mouse import Listener, Button
from pynput.keyboard import Key, Controller
 
class AutoCopier():
    __press_xy = (0, 0)  # 私有变量 鼠标左键按下时的位置
 
    def __init__(self):
        self.keyboard = Controller()                     # 初始化键盘控制器
        self.listener = Listener(on_click=self.on_click) # 初始化鼠标监听器
        self.listener.start()                            # 开启鼠标监听器线程
 
    # 点击函数
    def on_click(self, x, y, button, pressed):           
        if button == Button.left:             # 左键点击
            if pressed:                       # 左键按下
                self.__press_xy = (x, y)      # 记录当前鼠标位置
            else:                             # 左键松开           
                if self.__press_xy != (x, y): # 按下位置和松开位置不一致
                    self.copy()               # 说明操作是划词,执行复制函数
    
    # 复制函数
    def copy(self): 
        with self.keyboard.pressed(Key.ctrl): # 按下ctrl,with语句结束后自动松开
            self.keyboard.press('c')          # 按下c
            self.keyboard.release('c')        # 松开c
 
    # 等待线程终止
    def wait_to_stop(self):
        self.listener.join()
 
# for test
if __name__ == '__main__':
    at = AutoCopier()
    at.wait_to_stop()

知识点补充

1.pynput是什么

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

2.使用步骤

安装pynput模块

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

键盘控制

如下:

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);

鼠标控制

如下:

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)

关于“Python中用pynput制作划词复制功能的代码是什么”的内容今天就到这,感谢各位的阅读,大家可以动手实际看看,对大家加深理解更有帮助哦。如果想了解更多相关内容的文章,关注我们,群英网络小编每天都会为大家更新不同的知识。

群英智防CDN,智能加速解决方案
标签: python

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

猜你喜欢

成为群英会员,开启智能安全云计算之旅

立即注册
专业资深工程师驻守
7X24小时快速响应
一站式无忧技术支持
免费备案服务
免费拨打  400-678-4567
免费拨打  400-678-4567 免费拨打 400-678-4567 或 0668-2555555
在线客服
微信公众号
返回顶部
返回顶部 返回顶部
在线客服
在线客服