如何用 Python 编写 Alfred Workflow

如何用 Python 编写 Alfred Workflow

写这篇文章记录一下我第一次开发 Alfred Workflow 的历程,希望能给后来者提供一个真正有帮助的教程。

在这边文章里,我会讲述我如何在Alfred里开发一个workflow,来实现LeetCode上的问题和Topic的检索功能。具体的代码,说明和演示可以访问我的 Github.

先贴个一个简单的示例图
这里写图片描述

选择Binary Search Tree [Hard]后,会打开一个LeetCode页面并筛选出所有带有Binary Search Tree标签的Hard Problem,如下图所示:
这里写图片描述

1. 准备工作

首先使用Alfred的Workflow,必须要购买他们的Alfred Powerpack,还是很值得的。

具体开发需要的依赖库是:deanishe开发的Alfred Workflow组件,可以从Github上面把它下载下来。

2. Detail Steps

2.1 创建一个新的workflow

首先点击左下角的+号,选择创建一个Blank Workflow,如下图所示:
这里写图片描述

2.2 添加Alfred Workflow开发组件

接下来先创建一个Script Filter,如下图所示
这里写图片描述

进入workflow所在的文件夹,双击刚刚新创建的Script Filter,然后双击下图中红色圆圈中的按钮即可。
这里写图片描述

最后把下载好的Alfred Workflow开发组件里的workflow文件夹,拷贝到这个文件夹中,如下图所示:
这里写图片描述

2.3 编写Script

首先讲讲如何在Alfred Workflow中调用我们编写的Python脚本,双击Script Filter,配置如下所示:

扫描二维码关注公众号,回复: 1021902 查看本文章

这里写图片描述

/bin/bash表示使用bash来执行我们的脚本,script中所写的就是在bash中执行的命令,如上图中所示,我们执行了一个名为search.py的Python脚本,并传递了参数--topic "{query}". 其中{query}就是用户在Alfred中输入的字符串。

接下来就可以使用 Alfred Workflow 库来开发了,具体的教程可以查看链接中Github的说明。

下面讲一下简单的基本框架

#!/usr/bin/python
# encoding: utf-8

import sys

# Workflow3 supports Alfred 3's new features. The `Workflow` class
# is also compatible with Alfred 2.
from workflow import Workflow3


def main(wf):
    # The Workflow3 instance will be passed to the function
    # you call from `Workflow3.run`.
    # Not super useful, as the `wf` object created in
    # the `if __name__ ...` clause below is global...
    #
    # Your imports go here if you want to catch import errors, which
    # is not a bad idea, or if the modules/packages are in a directory
    # added via `Workflow3(libraries=...)`
    import somemodule
    import anothermodule

    # Get args from Workflow3, already in normalized Unicode.
    # This is also necessary for "magic" arguments to work.
    args = wf.args

    # Do stuff here ...

    # Add an item to Alfred feedback
    wf.add_item(u'Item title', u'Item subtitle')

    # Send output to Alfred. You can only call this once.
    # Well, you *can* call it multiple times, but subsequent calls
    # are ignored (otherwise the JSON sent to Alfred would be invalid).
    wf.send_feedback()


if __name__ == '__main__':
    # Create a global `Workflow3` object
    wf = Workflow3()
    # Call your entry function via `Workflow3.run()` to enable its
    # helper functions, like exception catching, ARGV normalization,
    # magic arguments etc.
    sys.exit(wf.run(main))

我们可以通过如下的方式来在Alfred的下拉列表中添加项:

wf.add_item(
    title="Title here",
    subtitle="Subtitle here",
    valid=True,
    uid="url here",
    arg="return argument here"
)

具体的代码,说明和演示可以访问我的 Github.

有什么问题可以在这里留言,看到了我会尽量回复。

猜你喜欢

转载自blog.csdn.net/Zzy_ZhangZeyu_/article/details/80374170