今天给大家介绍的项目是来自谷歌开源的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 3def hello(name="World"): 4 return "Hello %s!" % name 5 6if __name__ == __main__ : 7 fire.Fire(hello) 8 9 10# from the command line,then run: 11python hello.py # Hello World! 12python hello.py --name=David # Hello David! 13python hello.py --help # Shows usage information.
例子二
1# calling Fire on a class 2import fire 3 4class Calculator(object): 5 """A simple calculator class.""" 6 7 def double(self, number): 8 return 2 * number 9 10if __name__ == __main__ : 11 fire.Fire(Calculator) 12 13# from the command line, then run: 14 15python calculator.py double 10 # 20 16python calculator.py double --number=15 # 30
例子三
1#!/usr/bin/env python
2import fire
3class Example(object):
4 def hello(self, name= world ):
5 """Says hello to the specified name."""
6 return Hello {name}! .format(name=name)
7
8def main():
9 fire.Fire(Example)
10
11if __name__ == __main__ :
12 main()
13
14##########################
15 当 Fire 函数运行时,我们的命令被执行。
16仅仅通过调用 Fire,现在我们可以把样本类当作命令行工具来使用。
17
18
19$ ./example.py hello
20Hello world!
21
22$ ./example.py hello David
23Hello David!
24
25$ ./example.py hello --name=Google
26Hello Google!每个 Fire CLI 都带有交互模式。
- 运行 CLI 时使用「-interactive」旗标和命令行以及其他已定义的变量来登录 IPython REPL。
- 请务必查看 Python Fire 的文档,从而了解 Fire 更多实用的特征。
因为 Python Fire 十分简单、普遍和强大,我希望能为你的项目提供一个十分有效的库。
英文链接:http://opensource.googleblog.com/2017/03/python-fire-command-line.html
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。




