Google 的 Fire 轻松实现命令行小工具

来自谷歌博客

今天,我们高兴地宣布 Python Fire 将开放源代码。Python Fire 可根据任何 Python 代码生成命令行界面 (CLI)。只需在任何 Python 程序中调用 Fire 函数,便可自动将该程序转变成 CLI。这个内容库可通过“pip install fire”从 pypi 获得,其源代码在 GitHub 上公开。
Python Fire 可自动将您的代码转变成 CLI,无需您做任何额外工作。您不必定义参数,设置帮助信息,或者编写定义代码运行方式的 main 函数。相反,您只需从 main 模块调用“Fire”函数,其余工作全部交由 Python Fire 来完成。它利用检查将您提供的任何 Python 对象(无论是类、对象、字典、函数甚至整个模块)转变成一个 Tab 命令补全和文档齐备的命令行界面,并且这个 CLI 甚至能在代码发生变化时即时更新。
让我们通过一个简单的示例加以说明。

#!/usr/bin/env python
import fire
 class Example(object):
  def hello(self, name='world'):
    """Says hello to the specified name."""
    return 'Hello {name}!'.format(name=name)
 def main():
  fire.Fire(Example)
 if __name__ == '__main__':
  main()

运行 Fire 函数时将会执行我们的命令。现在我们只需调用 Fire,就可以将 Example 类当作命令行实用程序来使用。

 $ ./example.py hello
Hello world!
$ ./example.py hello David
Hello David!
$ ./example.py hello --name=Google
Hello Google!

当然,您可以继续像使用普通 Python 内容库那样使用此模块,从而能够从 Bash 和 Python 使用完全相同的代码。如果您要编写 Python 内容库,则试用就不再需要更新 main 方法或客户端;相反,您只需从命令行运行所试用的内容库片段。即使内容库发生变化,命令行工具也能即时更新。
在 Google,工程师们利用 Python Fire 根据 Python 内容库生成命令行工具。我们的一个图像处理工具就是将 Fire 与 Python 成像内容库 (PIL) 配合使用生成的。在 Google Brain 团队,我们使用的试验管理工具也是使用 Fire 生成的,通过它从 Python 或 Bash 管理试验的效果同样好。
每个 Fire CLI 都自带交互模式。运行 CLI 时带“–interactive”标志可启动一个 IPython REPL,其中包含命令的结果以及其他已经定义并可随时使用的有用变量。请务必查看 Python Fire 的文档,了解 Fire 提供的这项功能以及其他有用功能的更多信息。
考虑到 Python Fire 简单易用、通用性强并且功能强大,我们希望您能在自己的项目中发现它的用武之地。

仓库地址:https://github.com/google/python-fire

自己练手

# -*- coding: UTF-8 -*-

import sys
try:
    import requests
    import fire

except ImportError:

    print("Please install requests fire ")
    sys.exit(1)

def query(domain):

        url = "https://sapi.k780.com"

        querystring = {"app": "domain.beian", "domain": domain, "appkey": "xxx",
                       "sign": "xxxxx", "format": "json"}

        headers = {

            'Cache-Control': "no-cache",
        }

        response = requests.request("GET", url, headers=headers, params=querystring)

        res_json = response.json()

        issuccess = int(res_json['success'])

        isstatus = res_json['result']["status"]

        if issuccess == 1:

            if isstatus == "ALREADY_BEIAN":

                print("域名已备案")


            elif isstatus == "NOT_BEIAN":

                print("域名未备案")

            elif isstatus == "WAIT_PROCESS":

                print("等待系统处理")

        elif issuccess == 0:

            print("系统错误")


if __name__ == '__main__':

    fire.Fire(query)

效果

➜  www beian
Fire trace:
1. Initial component
2. ('The function received no value for the required argument:', 'domain')

Type:        function
String form: <function query at 0x10ee70378>
File:        Beian.py

Usage:       beian DOMAIN
             beian --domain DOMAIN
➜  www beian --domain baidu.com
域名已备案
➜  www beian awen.me
域名已备案
➜  www