1 什么是命令行接口?
参考博客[1]: 大家使用最多的命令行工具应该是pip
了,pip
提供了很多的命令行参数和选项,我们在终端使用pip install --help
命令可以查看install
子命令的帮助文档。
命令行接口通常以可执行文件的名称开头。我们只需在控制台中输入它的名称,然后访问脚本的主入口点,例如pip
。
我们可以通过命令行,将参数传递给脚本,它们可以是:
•Arguments (参数):这是传递给脚本的必需参数。如果您不提供它,则CLI会遇到错误。例如,pandas
是此命令中的参数:pip install pandas
。
•Options (选项):顾名思义,它是一个可选参数,通常包含一个名称和一个值对,例如pip install pandas --cache-dir ./my-cache-dir
。就是指定了./my-cache-dir
作为应使用的缓存目录。
•Flags (标志):这是一个特殊的选项参数,它告诉脚本启用或禁用某些行为。最常见的可能是--help
。
2 为什么需要命令行接口?
让很多人能轻松、简单、简洁地执行代码,而不需要手动修改代码,如频繁地修改某些参数。使用命令行接口可以将参数和代码分离开来。
所以,** Fire 就是用来生成命令行接口**(Command Line Interfaces, CLIs)的工具,有了它,我们可以:
Python Fire is a library for creating command line interfaces (CLIs) from absolutely any Python object.
Python Fire is a simple way to create a CLI in Python.
Python Fire is a helpful tool for developing and debugging Python code.
Python Fire helps with exploring existing code or turning other people’s code into a CLI.
Python Fire makes transitioning between Bash and Python easier.
Python Fire makes using a Python REPL easier by setting up the REPL with the modules and variables you’ll need already imported and created.
它是 一种面向广义对象的方式来玩转命令行,这种对象可以是类、函数、字典、列表等。
3 如何使用Fire?
首先,安装Fire包:pip install fire
;
3.1 使用函数
以多个函数为例,单个函数的情况是一样的。假设有个 test-fire-2func.py
的文件[2]:
import fire
import datetime
def cal_days(date_str1, date_str2):
'''计算两个日期之间的天数'''
date_str1 = str(date_str1)
date_str2 = str(date_str2)
d1 = datetime.datetime.strptime(date_str1, '%Y%m%d')
d2 = datetime.datetime.strptime(date_str2, '%Y%m%d')
delta = d1 - d2
return delta.days
def days2today(date_str):
'''计算某天距离今天的天数'''
date_str = str(date_str)
d = datetime.datetime.strptime(date_str, '%Y%m%d')
delta = datetime.datetime.now() - d
return delta.days
if __name__ == '__main__':
fire.Fire()
使用 fire.Fire() 来生成 CLIs. 在命令行窗口中输入:
$ python test-fire-2func.py days2today 20170401
21
$ python test-fire-2func.py cal_days 20170422 20170401
21
即可使用 test-fire-2func.py
文件各个函数中的功能。
3.2 使用类
如在以下的例子example.py
中,将类 作为 fire.Fire的入参:fire.Fire(BrokenCalculator)
。
import fire
class BrokenCalculator(object):
def __init__(self, offset=1):
self._offset = offset
def add(self, x, y):
return x + y + self._offset
def multiply(self, x, y):
return x * y + self._offset
if __name__ == '__main__':
fire.Fire(BrokenCalculator)
于是有:
$ python example.py add 10 20
31
$ python example.py multiply 10 20
201
$ python example.py add 10 20 --offset=0
30
$ python example.py multiply 10 20 --offset=0
200
4 Reference
[1] https://ask.hellobi.com/blog/wangdawei/36677
[2] https://blog.youkuaiyun.com/u010099080/article/details/70332074
[3] https://www.zhihu.com/people/prodesire 【这里有比较完整关于python命令行,包括Fire、argparse、click等的介绍】