在python中,命令行接口常用的argparse 和click,但是相对于python-fire 来说灵活度太缺了,fire可以直接将python中的函数,以命令行显示.
简单的介绍几个例子:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#filename: fire-demo.py
__author__ = 'xijun1'
import fire
def demo(param):
"""
just a demo
:param param: any str
:return:
"""
print "hello {} !".format(param)
return;
if __name__ == '__main__':
fire.Fire()
执行的格式为: python 如果fire.Fire()没有指定名称时:
需要在执行命令行时,带入函数名: python fire-demo.py demo ,同时,如果函数有参数是,需要输入参数,不然会不错,并提示:
1 python_demo python fire-demo.py demo
2 Fire trace:
3 1. Initial component
4 2. Accessed property "demo"
5 3. ('The function received no value for the required argument:', 'param')
6
7 Type: function
8 String form: <function demo at 0x10e424c80>
9 File: ~/github/python_demo/fire-demo.py
10 Line: 20
11 Docstring: just a demo
12 :param param: any str
13 :return:
14
15 Usage: fire-demo.py demo PARAM
16 fire-demo.py demo --param PARAM
如果带入参数: python fire-demo.py demo “google”
1 python_demo python fire-demo.py demo "google"
2 hello google !
或者我们也可以这样:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'xijun1'
import fire
def demo(param):
"""
just a demo
:param param: any str
:return:
"""
print "hello {} !".format(param)
return;
if __name__ == '__main__':
fire.Fire(demo)
只需要执行:
python_demo python fire-demo.py google
hello google !
当我们面对一个类Class的时候:
class ho:
def __init__(self,type):
self.type = type
pass
def hodemo(self, param):
"""
:param param: any string
:return:
"""
print "{} hello {} !".format( self.type,param)
return;
我们只需要执行:
python_demo python fire-demo.py ho --type "gxjun" hodemo "google"
gxjun hello google !
当然我们也可以将类写入Fire中:
python_demo python fire-demo.py --type gxjun hodemo google
gxjun hello google !