1. 单个函数
之前已经简单介绍过了 Fire 使用,那么这边文章我们看下 Fire 其他的使用方式,还是以我们之前hello例子开始。
import firefrom typing import Textdef hello(name: Text = "World") -> Text:"""Hello function:param name: Any text:return: str"""return f"Hello {name}!"if __name__ == '__main__':fire.Fire(hello) # 或者直接使用 fire.Fire() 也可以
除非所有函数都需要添加 CLI,否则不建议使用fire.Fire(),推荐将指定函数进行添加。
除了之前介绍的python hello.py --help,也可以使用python hello.py hello --help来查看具体函数的帮助信息。同时,我们还可以直接运行脚本,或者给脚本添加参数:
$ python hello.pyHello World!$ python hello.py yumingminHello yumingmin!$ python hello.py --name=yumingminHello yumingmin!
2. 多个函数
那么 Fire 可不可以给多个函数对象添加命令行接口呢,当然是可以的。如果 Python 文件已经包含了多个函数,那么直接使用fire.Fire()即可(但不推荐),请看下面示例:
import firefrom typing import Textdef add(x: int, y: int) -> int:return x + ydef multiply(x: int, y: int) -> int:return x * yif __name__ == '__main__':fire.Fire({'add': add,'multiply': multiply,})
具体使用方法如下:
$ python hello.py add 10 2030$ python helloFire.py multiply --x=10 --y=20200
3. 带和*参数的函数
import firedef order_by_length(*items):"""Orders items by length, breaking ties alphabetically."""sorted_items = sorted(items, key=lambda item: (len(str(item)), str(item)))return ' '.join(sorted_items)if __name__ == '__main__':fire.Fire(order_by_length)
直接注意的是,如果这里我们需要调用链式函数的话,我们需要添加-(默认情况是-,也可以通过-- --separator=来进行修改),否则函数会被当作参数被传递进去:
$ python example.py dog cat elephant uppercat dog upper elephant$ python example.py dog cat elephant - upperCAT DOG ELEPHANT$ python example.py dog cat elephant X upper -- --separator=XCAT DOG ELEPHANT
