简介
目前 python 命令行解析库用过的有: argparse(python 自带),click(Flask 作者写的)
但二者相比 fire 这个库, 用起来都不够 "简单",fire 一行代码能把函数导出到命令行窗口.
argparse 用法示例
- # arg_test.py
- import argparse
- def counter(file_type=None):
- return {file_type: 100}
- # 初始化解析器
- parser = argparse.ArgumentParser()
- # 定义参数
- parser.add_argument("-f", "--file", help="统计指定文件类型")
- # 解析
- args = parser.parse_args()
- print(counter(args.file))
运行:
- $ python arg_test.py -f python
- {
- 'python': 100
- }
click 用法示例
- # firetest.py
- import click
- @click.command()
- @click.option("-f", "--file", help="统计制定文件类型")
- def counter(file=None):
- click.echo({file: 100})
- if __name__ == '__main__':
- print(counter())
运行:
- $ python firetest.py -f python
- {
- u'python': 100
- }
fire 安装
- # pip 安装: pip install fire
- # conda 安装: conda install fire -c conda-forge
- # 源码安装: Git 拿到代码, 执行: python setup.py install
fire 使用示例
通常: python [文件名] [函数名] [参数]
官方文档: https://github.com/google/python-fire/blob/master/docs/guide.md
fire.Fire()
直接在程序中调用 fire.Fire(), 不需要修改目标函数, fire 会把当前模块下的所有对象导出到命令行中
- # firetest.py
- import fire
- def foo(name):
- return 'foo {name}!'.format(name=name)
- def bar(name):
- return "bar {name}".format(name=name)
- if __name__ == '__main__':
- fire.Fire()
运行:
- # 调用方式: python [文件名] [函数名] [参数]
- # 函数名后面直接跟参数值
- $ python firetest.py foo hello
- foo hello!
- # 也可以显示地先指定参数名, 再跟参数值
- $ python firetest.py bar --name hello
- bar hello!
- fire.Fire(<function>)
可以指定某个函数导出到命令行
- import fire
- def foo(name):
- return 'foo {name}!'.format(name=name)
- if __name__ == '__main__':
- fire.Fire(foo)
运行:
- # 调用方式: python [函数名] [参数]
- $ python firetest.py hello
- foo hello!
当 Fire 接收函数 foo 作为参数时, 只加载 foo 函数到命令行中, 此时, 在命令行中运行时也无需再指定函数名字, 只需要指定参数就好.
fire.Fire(<dict>)
Fire 不仅可以接收函数, 还可以接收字典对象作为参数, 可在字典中配置那些函数需要导出到命令行中.
例如, 有加减乘 3 个函数, 我们可以选择性的选择其中 2 个导出到命令行:
- import fire
- def add(x, y):
- return x + y
- def multiply(x, y):
- return x * y
- def subtract(x, y):
- return x - y
- if __name__ == '__main__':
- fire.Fire({
- 'add': add,
- 'subtract': subtract,
- })
运行:
- $ python firetest.py add 1 4
- 5
- $ python firetest.py subtract 1 4
- -3
- $ python firetest.py multiply 1 4
- # multiply 会报错, 因为没有导出
- fire.Fire(<object>)
还可以接收类的实例对象
- import fire
- class Calculator(object):
- def add(self, x, y):
- return x + y
- def multiply(self, x, y):
- return x * y
- if __name__ == '__main__':
- calculator = Calculator()
- fire.Fire(calculator)
运行:
- $ python firetest.py add 10 20
- 30
- $ python firetest.py multiply 10 20
- 200
参考文章: https://mp.weixin.qq.com/s/lMOieL_RFRHsh5OW4G4axg
来源: http://www.bubuko.com/infodetail-3625477.html