Python程序员联盟

python 脚本自动生成命令行接口(CLI)之Fire

2017-12-16  本文已影响22人  一只老梨花

起因

工作中总是需要在调用python 脚本的时候把一些变量传进去,比如python my_script.py arg1 arg2. 看了一些网上的方案之后觉得sys.args 传参太简单了,没有参数说明,argparse的参数说明又要自己写,比较麻烦。

Fire

Fire 是Google 开发的一款自动生产python脚本CLI的python lib。使用方法很简单。

eg:test.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2017-12-16 11:56:17
# @Author  : robin (robin.zhu@*********)

import os,fire

def a1(name,age,sex):
    print name
    print age
    print sex

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

python test.py robin 11 man
or
python test.py --age 11 --name robin --sex man

输入python test.py
返回:

Fire trace:
1. Initial component
2. ('The function received no value for the required argument:', 'name')

Type:        function
String form: <function a1 at 0x0000000003E63048>
File:        d:\userdata\robzhu\desktop\work_script\fire\test.py
Line:        29

Usage:       test.py NAME AGE SEX
             test.py --name NAME --age AGE --sex SEX

一个fire.Fire()已经为你做好了。

Tips:

Fire 也可以传入class,如果class 有构造函数,对应的参数也需要一起传入。

参考:

Fire

上一篇下一篇

猜你喜欢

热点阅读