用python做一个剪切板助手

用Python做剪切板助手


在日常的学习和编程过程当中,单纯的Ctrl+C/V已经没办法满足我了,有时候复制粘贴需要来回切换界面,导致效率不高,所以用Python做了一个剪切板助手,来降低切换界面和使用Ctrl+C/V的频率。
本例采用了Thread多线程的方式,使得python程序能够实时的检测我的剪切板,并对检测到的剪切板内容进行修饰、更改、填充。利用了python的pyperclip库和threading库

程序效果图:

模式1
模式2
模式3

import time
import pyperclip
from threading import Thread

一、构造多线程类

因为要对剪切板的内容进行实时监控、更改,因此至少需要用到两个线程,保证监控函数和剪切板内容更改函数两者互不耽误。这里,简单重构一下Thread类,让我们的函数能够根据我们的意愿开始运行。

class MyThread(Thread):
    def __init__(self, func):
        super().__init__()
        self.func = func

    def run(self):
        self.func()

二、构造剪切助手类

剪切板检测变化函数

首先,为了使得程序在后台运行后能够对剪切板进行一通操作,就必须使其能够检测到剪切板的变化,因而需要用剪切板之前的内容与当前的内容进行对比,如果不同,这说明发生了变化。因而:

def test_change(self):
    # 此处可以修改为 在发现剪切板内容更改后,未进行处理之前,此段时间内是否停止剪切板服务
    # 此处未加修改,可能出现部分内容未能及时处理的情况
    while True:
        time.sleep(0.05)
        # print("我正在进行检测....")
        now_perclip_content = pyperclip.paste()
        if now_perclip_content == self.old_perclip_content:
            # print("未检测到剪切板内容更改.....")
            self.change_factor = False
        else:
            # print("检测到剪切板内容更改.....")
            self.change_factor = True

如果检测到内容的变化,通过类属性change_factor能够实时的传递时候有剪切板变化,以利于下一步的一通操作。此处程序休眠50ms是为了提高效率,防止死机。

剪切板操作函数

在test_change()函数在对剪切板内容进行实时监控的过程中,需要在另外一个线程运行我们的剪切板操作函数对剪切板进行一通又一通的操作,明显,两者就行沟通的桥梁就是change_factor属性,通过这个属性,剪切板操作函数知道剪切板内容更改后,开始对剪切板进行操作。如下:

def do_the_thing(self, func):
    while True:
        time.sleep(0.05)
        if self.change_factor:
            func()

其中函数func()即为对剪切板的操作模式,下文提及。

程序运行函数

监控函数和操作函数构造好之后,需要两者开始进行多线程的运行,这里构造一个新的函数,对两个函数构造MyThread类,并使之开始运行。如下:

def run(self, flag):
    print("模式%d正在运行...." % flag)
    test_change_thread = MyThread(self.test_change)
    test_change_thread.start()
    thread_do_thing = MyThread(self.do_the_thing(self.flags[flag]))
    thread_do_thing.start()
操作模式函数

上文我们已经将基本框架构造完成,下面就是核心的内容,也就是对剪切板内容的更改方式,这里,将我已经写好的几种操作模式贴出来,书友们如果有其他操作模式的想法,可以自己写出来,带入上文的基本框架即可使用。

def formation(self):
    """
     多行复制,自动成表。
    """
    tem_content = ""
    now_perclip_content = pyperclip.paste()
    self.FORMATIONNUM += 1
    tem_content += "%d." % self.FORMATIONNUM + " " + now_perclip_content + '\n'
    self.old_perclip_content += tem_content
    pyperclip.copy(self.old_perclip_content)

def para2order(self):
    """
    标号自加,有序成段。
    """
    tem_content = ""
    now_perclip_content = pyperclip.paste()
    if now_perclip_content != "":
        if self.PARMBEGIN:
            if now_perclip_content[-1] not in [".", "。"]:
                tem_content += "      " + now_perclip_content + '。'
            else:
                tem_content += "      " + now_perclip_content
            self.PARMBEGIN = False
        else:
            if now_perclip_content[-1] not in [".", "。"]:
                tem_content += now_perclip_content + '。'
            else:
                tem_content += now_perclip_content
    self.old_perclip_content += tem_content
    pyperclip.copy(self.old_perclip_content)

def num2order(self):
    # 一次复制,多次粘贴,数字成序。
    pass

def en2title(self):
    """
    英文单词自成标题形式。
    """
    tem_content = ""
    now_perclip_content = pyperclip.paste()
    tem_content += now_perclip_content.title()
    self.old_perclip_content = tem_content
    pyperclip.copy(self.old_perclip_content)

其中的“一次复制,多次粘贴,数字成序。”模式,由于个人能力原因,还没有想出解决方案,我的想法就是比如我对"name1"复制后,第一次粘贴为"name1",第二次粘贴就位"name2"…周此以往,第N次粘贴出来就是"nameN"。如果有大神愿意指导一番的话,可以加本人qq:676977060。

三、实例类并让程序工作

以上我们构造了类并且写了多个剪切板操作模式,接下来就需要实例类,并开始让我们的程序运行起来,然后对剪切板进行操作,因此还需要一个主函数作为入口,使得程序运行。如下:

def main():
    shearer = ShearerNew()

    print("以下数字代表模式\n"
          "0: 多行复制,自动成表。\n"
          "1: 标号自加,有序成段。\n"
          "2: 英文单词自成标题形式。\n"
          "3: 一次复制,多次粘贴,数字成序。")

    try:
        flag = int(input("请输入一个0-3的数字: "))
        if flag not in range(1, 4):
            raise Exception
    except:
        print("输入数字格式有误,自动为0号模式")
        flag = 0

    shearer.run(flag)

以上就是剪切板助手的整个运行原理。

程序全代码

贴出全代码,需要用到time库、threading库、pyperclip库。安装方式,使用pip即可。

import time
import pyperclip
from threading import Thread


class MyThread(Thread):
    def __init__(self, func):
        super().__init__()
        self.func = func

    def run(self):
        self.func()


class ShearerNew:
    FORMATIONNUM = 0
    PARMBEGIN = True

    def __init__(self):
        self.empty_shearer()
        self.old_perclip_content = ""
        self.change_factor = False
        self.flags = [self.formation, self.para2order, self.en2title, self.num2order]

    @staticmethod
    def empty_shearer():
        pyperclip.copy("")

    def test_change(self):
        # 此处可以修改为 在发现剪切板内容更改后,未进行处理之前,此段时间内是否停止剪切板服务
        # 此处未加修改,可能出现部分内容未能及时处理的情况
        while True:
            time.sleep(0.05)
            # print("我正在进行检测....")
            now_perclip_content = pyperclip.paste()
            if now_perclip_content == self.old_perclip_content:
                # print("未检测到剪切板内容更改.....")
                self.change_factor = False
            else:
                # print("检测到剪切板内容更改.....")
                self.change_factor = True

    def do_the_thing(self, func):
        while True:
            time.sleep(0.05)
            if self.change_factor:
                func()

    def run(self, flag):
        print("模式%d正在运行...." % flag)
        test_change_thread = MyThread(self.test_change)
        test_change_thread.start()
        thread_do_thing = MyThread(self.do_the_thing(self.flags[flag]))
        thread_do_thing.start()

    def formation(self):
        """
         多行复制,自动成表。
        """
        tem_content = ""
        now_perclip_content = pyperclip.paste()
        self.FORMATIONNUM += 1
        tem_content += "%d." % self.FORMATIONNUM + " " + now_perclip_content + '\n'
        self.old_perclip_content += tem_content
        pyperclip.copy(self.old_perclip_content)

    def para2order(self):
        """
        标号自加,有序成段。
        """
        tem_content = ""
        now_perclip_content = pyperclip.paste()
	    if now_perclip_content != "":
            if self.PARMBEGIN:
                if now_perclip_content[-1] not in [".", "。"]:
                    tem_content += "      " + now_perclip_content + '。'
                else:
                    tem_content += "      " + now_perclip_content
                self.PARMBEGIN = False
            else:
                if now_perclip_content[-1] not in [".", "。"]:
                    tem_content += now_perclip_content + '。'
                else:
                    tem_content += now_perclip_content
        self.old_perclip_content += tem_content
        pyperclip.copy(self.old_perclip_content)

    def num2order(self):
        # 一次复制,多次粘贴,数字成序。
        pass

    def en2title(self):
        """
        英文单词自成标题形式。
        """
        tem_content = ""
        now_perclip_content = pyperclip.paste()
        tem_content += now_perclip_content.title()
        self.old_perclip_content = tem_content
        pyperclip.copy(self.old_perclip_content)


def main():
    shearer = ShearerNew()

    print("以下数字代表模式\n"
          "0: 多行复制,自动成表。\n"
          "1: 标号自加,有序成段。\n"
          "2: 英文单词自成标题形式。\n"
          "3: 一次复制,多次粘贴,数字成序。")

    try:
        flag = int(input("请输入一个0-3的数字: "))
        if flag not in range(1, 4):
            raise Exception
    except:
        print("输入数字格式有误,自动为0号模式")
        flag = 0

    shearer.run(flag)


if __name__ == "__main__":
    main()
发布了8 篇原创文章 · 获赞 19 · 访问量 551

猜你喜欢

转载自blog.csdn.net/evil126126/article/details/105578741