在python原生编程中,我们常用sys.argv[1]
来传递命令行下的参数,对单个函数而言,fire
的操作也是类似,在__main__
里定义fire.Fire(函数名)
对象即可。但是在类上面,fire
就显得非常高效。下面具体介绍。
0. 简介
开源地址:google/python-fire
python-fire
是谷歌开源的一款自动生成命令行(cli)界面的库。
1. 安装
pip install fire
2. 使用
Fire
支持任何python类型,比如函数、类、模块、对象、字典、列表、元组等等。
函数示例:
import fire
def hello(name="World"):
return "Hello %s!" % name
if __name__ == '__main__':
fire.Fire(hello)
终端使用方法:
python hello.py # Hello World!
python hello.py --name=David # Hello David!
python hello.py --help # Shows usage information.
对类的操作演示:
import fire
class Calculator(object):
"""A simple calculator class."""
def double(self, number):
return 2 * number
if __name__ == '__main__':
fire.Fire(Calculator)
终端使用方法:
python calculator.py double 10 # 20
python calculator.py double --number=15 # 30
从这里可见该工具的强大之处,对于一些python模块编程,我们只需添加简单的两行内容,就可以转换为一个Cli命令工具。这在最终生产环境是非常高效的。
3. 小结
fire
非常适合将python的类转换为Cli工具,用于单一函数也是没有问题的,不过这个工具仅在最后才可以使用,平时调试或者在jutyper
里是不行的,会提示ERROR:Could not consume arg
的错误。