[popexizhi] 看别人代码时发现,fire.Fire() 很好用:)
参考: http://developers.googleblog.cn/2017/03/python-fire.html
参考: http://developers.googleblog.cn/2017/03/python-fire.html
Python Fire 可自动将您的代码转变成 CLI,无需您做任何额外工作。您不必定义参数,设置帮助信息,或者编写定义代码运行方式的 main 函数。相反,您只需从 main 模块调用“Fire”函数,其余工作全部交由 Python Fire 来完成。它利用检查将您提供的任何 Python 对象(无论是类、对象、字典、函数甚至整个模块)转变成一个 Tab 命令补全和文档齐备的命令行界面,并且这个 CLI 甚至能在代码发生变化时即时更新。
让我们通过一个简单的示例加以说明。
#!/usr/bin/env python
import fire
class Example(object):
def hello(self, name='world'):
"""Says hello to the specified name."""
return 'Hello {name}!'.format(name=name)
def main():
fire.Fire(Example)
if __name__ == '__main__':
main()
运行 Fire 函数时将会执行我们的命令。现在我们只需调用 Fire,就可以将 Example 类当作命令行实用程序来使用。
$ ./example.py hello
Hello world!
$ ./example.py hello David
Hello David!
$ ./example.py hello --name=Google
Hello Google!
当然,您可以继续像使用普通 Python 内容库那样使用此模块,从而能够从 Bash 和 Python 使用完全相同的代码。如果您要编写 Python 内容库,则试用就不再需要更新 main 方法或客户端;相反,您只需从命令行运行所试用的内容库片段。即使内容库发生变化,命令行工具也能即时更新。
没有评论:
发表评论