FreezeJ' Blog

用python fire模块快速构建CLI工具

2022-01-06

官方文档
https://github.com/google/python-fire
https://github.com/google/python-fire/blob/master/docs/guide.md

写简单的命令行脚本,初学时使用sys.argv来抠命令行参数,需要很多判断并且很繁琐,难以实现复杂的需求。后来学习了argparse,能更加细致的定义参数类型、可选项、提示等,对于比较复杂的参数、选项也能满足,但是看到fire模块,还是让人眼前一亮。
由谷歌开源的fire模块,直接从函数或者类的定义中,反向生成需要的参数,对于轻量的脚本非常友好,不用写过多的参数定义、获取代码,但是又能实现简单的控制和参数提示。有点小遗憾就是要独立安装,不在默认的python库里。

安装

pip3 install fire

调用函数

import fire

def choice(num:int=0):
    """
    test fire doc
    """
    if num:
       return f'you choice {num}'
    else:
       return f'default choice {num}'

if __name__ == '__main__':
    fire.Fire(choice)

显示帮助:

$ python3 test_fire1.py -- --help  
NAME
    test_fire1.py - test fire doc

SYNOPSIS
    test_fire1.py <flags>

DESCRIPTION
    test fire doc

FLAGS
    --num=NUM
        Type: int
        Default: 0

使用默认值

$ python3 test_fire1.py                                                                                                                
default choice 0

传递参数

$ python3 test_fire1.py --num=1                                                                                                        
you choice 1

调用类实例

import fire

class Calculator(object):
  """简单计算器类"""

  def double(self, number:int):
    """幂运算"""
    return 2 * number

  def sum(self, number_list:list):
    """数字列表求和"""
    return sum(number_list)

if __name__ == '__main__':
  c = Calculator()
  fire.Fire(c)

显示帮助

$ python3 test_fire2.py -- --help                                                                                                      
NAME
    test_fire2.py - 简单计算器类

SYNOPSIS
    test_fire2.py COMMAND

DESCRIPTION
    简单计算器类

COMMANDS
    COMMAND is one of the following:

     double
       幂运算

     sum
       数字列表求和

调用实例方法

$ python3 test_fire2.py double 2                                                                                                       
4 
$ python3 test_fire2.py sum "[1,2,3,4,5]"                                                                                              
15

fire会自动转换参数类型

直接调用

test1 = '测试'
test2 = [1, 2, 3]
test3 = lambda x: x + 1
$ python3 -m fire test_fire3.py -- --help                                                                                              
NAME
    test_fire3.py

SYNOPSIS
    test_fire3.py GROUP | COMMAND | VALUE

GROUPS
    GROUP is one of the following:

     test2

COMMANDS
    COMMAND is one of the following:

     test3

VALUES
    VALUE is one of the following:

     test1

$ python3 -m fire test_fire3.py test1                                                                                                  
测试

$ python3 -m fire test_fire3.py test2                                                                                                  
1
2
3

$ python3 -m fire test_fire3.py test3 2                                                                                                
3

这里只列举了常用的方法,更详细的的用法请翻阅官方文档。

Tags: Python