浅谈Wox插件的编写

作者: 煎煎煎饼 | 来源:发表于2019-02-19 17:38 被阅读63次

    之前写过一篇使用Wox+Python打造命令行工具库,除了我们自定义命令行工具之外,Wox的强大之处,在于它的插件功能,可以安装第三方插件以及自行设计编写插件。我们常用的程序搜索,网页搜索,其实都是插件。

    所以我们这一篇来聊聊如何编写Wox的插件

    在进入正题之前,先简单说说插件的安装方式和运行原理

    安装方式

    Wox目前支持以下几种安装插件的方式。

    使用wpm命令安装官方仓库的插件

    Wox内置了wpm插件,专门用于管理插件。

    安装插件:wpm install <插件名字>
    
    删除插件: wpm uninstall <插件名字>
    
    查看已安装插件: wpm list
    

    通过wox文件安装

    下载Wox插件包,以将插件安装包下载到本地(以.wox结尾),然后将插件安装包拖拽到Wox搜索框上即可开始安装。

    通过源码安装

    下载插件源码,放到Wox的Plugins目录下
    C:\Users\Administrator\AppData\Local\Wox\app-1.3.524\Plugins

    运行原理

    Wox与插件之间通过标准输入输出的方式通信,使用JSONRPC来完成通信。使用这种方式,将极大的提高Wox支持的插件种类, 几乎任何语言都可以用来编写Wox插件。

    编写插件

    先来看看一个Hello World 插件,插件目录


    ico.ico 插件图标
    plugin.json 文件包含了该插件的一些基本信息

    {
        "ID":"2f4e384e-76ce-45c3-aea2-b16f5e5c328f",
        "ActionKeyword":"h",
        "Name":"Hello World",
        "Description":"Hello World",
        "Author":"jianbing",
        "Version":"1.0.0",
        "Language":"python",
        "Website":"https://github.com/jianbing",
        "IcoPath":"Images\\ico.ico",
        "ExecuteFileName":"main.py"
    }
    
     
    
    
    字段 含义
    ID 32位UUID
    ActionKeyword 激活关键字
    Language 注意,不能写成py
    IcoPath Icon所在路径
    ExecuteFileName 入口文件

    main.py 核心文件

    # -*- coding: utf-8 -*-
    from wox import Wox, WoxAPI
    import pyperclip
    
    class Main(Wox):
    
        def query(self, keyword):
            results = list()
            results.append({
                "Title": "input",
                "SubTitle": keyword,
                "IcoPath": "Images/ico.ico",
                "JsonRPCAction": {
                    "method": "test_func",
                    "parameters": [keyword],
                    "dontHideAfterAction": False      # 运行后是否隐藏Wox窗口
                }
            })
            return results
    
        def test_func(self, keyword):
            pyperclip.copy(keyword)
    
    if __name__ == "__main__":
        Main()
    

    运行效果:


    回车后,“hello”这个字符串就被复制到剪贴板中,可以到另外的文本区域进行粘贴,看似非常完美

    问题来了,如果出现报错,比如导入的模块名错了

    import pyperclip1
    

    Wox就默默呆住了



    这样没有任何报错信息记录,对于代码编写和调试都是非常麻烦的

    经过一番尝试,折腾出了Hello World Ex

    看看新的目录结构,增加了一个util.py文件



    util.py 封装了捕获报错所需的相关类库和函数,以及简易的日志功能

    # -*- coding: utf-8 -*-
    
    from wox import Wox, WoxAPI
    import types
    import traceback
    import logging
    import functools
    import os
    from contextlib import contextmanager
    
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename="error.log",
                        filemode='a')
    
    class Log:
        @classmethod
        def debug(cls, msg):
            logging.debug(msg)
    
        @classmethod
        def info(cls, msg):
            logging.info(msg)
    
        @classmethod
        def error(cls, msg):
            logging.error(msg)
    
    @contextmanager
    def load_module():
        try:
            yield
        except:
            Log.error(traceback.format_exc())
            os.system(r'explorer "{}"'.format(os.getcwd()))
    
    
    def debug(func):
        @functools.wraps(func)
        def wrap(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except:
                error = traceback.format_exc()
                WoxAPI.show_msg("error", error)
                Log.error(error)
                os.system(r'explorer "{}"'.format(os.getcwd()))
    
        return wrap
    
    class DebugMeta(type):
        def __new__(cls, clsname, bases, attrs):
            for func_name, func in attrs.items():
                if isinstance(func, types.FunctionType):
                    attrs[func_name] = debug(func)
            return super(DebugMeta, cls).__new__(cls, clsname, bases, attrs)
    

    main.py 做相应的修改,其实修改并不多

    # -*- coding: utf-8 -*-
    from util import Wox, WoxAPI, load_module, Log, DebugMeta
    
    # 统一加载模块
    with load_module():
        import pyperclip
    
    class Main(Wox, metaclass=DebugMeta):  
    
        def query(self, keyword):
            results = list()
            results.append({
                "Title": "input",
                "SubTitle": keyword,
                "IcoPath": "Images/ico.ico",
                "JsonRPCAction": {
                    "method": "test_func",
                    "parameters": [keyword],
                    "dontHideAfterAction": False
                }
            })
            return results
    
        def test_func(self, keyword):
            pyperclip.copy(keyword)
    
    if __name__ == "__main__":
        Main()
    

    再来试试报错,还是刚刚的导入模块名字错误

    with load_module():
        import pyperclip1
    

    运行的时候,会自动弹出报错文件


    打开文件,可以看到完整的报错信息

    Tue, 19 Feb 2019 17:33:16 util.py[line:29] ERROR Traceback (most recent call last):
      File "C:\Users\Administrator\AppData\Roaming\Wox\Plugins\Hello World Ex-991dfc7a-7c37-41f7-8e63-273f83c9680f\util.py", line 35, in load_module
        yield
      File "C:\Users\Administrator\AppData\Roaming\Wox\Plugins\Hello World Ex-991dfc7a-7c37-41f7-8e63-273f83c9680f\main.py", line 7, in <module>
        import pyperclip1
    ModuleNotFoundError: No module named 'pyperclip1'
    

    再来试试方法里边的报错看看

    def test_func(self, keyword):
        raise Exception("error!!!")
        pyperclip.copy(keyword)
    

    回车后,弹出了报错文件所在目录后,右下角也会弹窗显示报错信息


    大功告成~

    插件的应用

    通过自定义插件,我们可以将一些操作集成上去,举个栗子,物品道具的查找,不在需要打开道具配置表进行搜索了~


    源码下载

    HelloWord和HelloWordEx的源码已经上传到了GitHub,欢迎围观

    相关文章

      网友评论

        本文标题:浅谈Wox插件的编写

        本文链接:https://www.haomeiwen.com/subject/bdufyqtx.html