今天给大家介绍的项目是来自谷歌开源的Python Fire,可以从任何 Python 代码生成命令行接口(command line interfaces (CLIs)),简单地调用任意 Python 程序中的 Fire 函数以将那个程序自动地转化为 CLI。截止发稿前,该项目已经在github获得15600+⭐,接近1000次fork。为什么这个项目这么火爆呢?俩字:『好用』......
Github地址https://github.com/google/python-fire
获取方式:
  • 从 pypi 获取 `pip install fire`
  • 从conda获取`
    conda install fire -c conda-forge
    `

  • 从源码安装, clone代码库 & `python setup.py install`
Python Fire有哪些优点:
  • 不需要定义参数、设置帮助信息或写一个主函数定义代码如何运行。只需从主模块调用 `Fire` 函数即可;
  • 将任何 Python 对象(类、对象、字典、函数,甚至整个模块)转化为命令行接口,并输出标注标签和文档;
  • 指令行界面会随着编码的变化保持实时更新。
例子一
1# calling Fire a function 2import
 fire
3defhello(name="World"): 4return"Hello %s!"
 % name
5 6if
 __name__ == 
__main__
:
7
  fire.Fire(hello)
8 910# from the command line,then run:11
python hello.py  
# Hello World!12
python hello.py --name=David  
# Hello David!13
python hello.py --help  
# Shows usage information.
例子二
1# calling Fire on a class 2import
 fire
3 4classCalculator(object): 5"""A simple calculator class.""" 6 7defdouble(self, number): 8return2
 * number
910if
 __name__ == 
__main__
:
11
  fire.Fire(Calculator)
1213# from the command line, then run:1415
python calculator.py double 
10# 2016
python calculator.py double --number=
15# 30
例子三
1#!/usr/bin/env python 2import
 fire
3classExample(object): 4defhello(self, name= world ): 5"""Says hello to the specified name.""" 6return
  Hello {name}! .format(name=name)
7 8defmain(): 9
 fire.Fire(Example)
1011if
 __name__ ==  __main__ :
12
 main()
1314##########################15
当 Fire 函数运行时,我们的命令被执行。

16
仅仅通过调用 Fire,现在我们可以把样本类当作命令行工具来使用。
171819
$ ./example.py hello
20
Hello world!
2122
$ ./example.py hello David
23
Hello David!
2425
$ ./example.py hello --name=Google
26
Hello Google!
每个 Fire CLI 都带有交互模式。
  • 运行 CLI 时使用「-interactive」旗标和命令行以及其他已定义的变量来登录 IPython REPL。
  • 请务必查看 Python Fire 的文档,从而了解 Fire 更多实用的特征。
因为 Python Fire 十分简单、普遍和强大,我希望能为你的项目提供一个十分有效的库。
英文链接:http://opensource.googleblog.com/2017/03/python-fire-command-line.html
推荐阅读
继续阅读
阅读原文