15600+星的 Python Fire为什么这么火,用完你就知道了
今天给大家介绍的项目是来自谷歌开源的Python Fire,可以从任何 Python 代码生成命令行接口(command line interfaces (CLIs)),简单地调用任意 Python 程序中的 Fire 函数以将那个程序自动地转化为 CLI。截止发稿前,该项目已经在github获得15600+⭐,接近1000次fork。为什么这个项目这么火爆呢?俩字:『好用』......
Github地址:https://github.com/google/python-fire
获取方式:
- 从 pypi 获取 `pip install fire`
- 从conda获取`conda install fire -c conda-forge`
- 从源码安装, clone代码库 & `python setup.py install`
Python Fire有哪些优点:
- 不需要定义参数、设置帮助信息或写一个主函数定义代码如何运行。只需从主模块调用 `Fire` 函数即可;
- 将任何 Python 对象(类、对象、字典、函数,甚至整个模块)转化为命令行接口,并输出标注标签和文档;
- 指令行界面会随着编码的变化保持实时更新。
例子一
fire
3defhello(name="World"): 4return"Hello %s!" % name
5 6if __name__ ==
__main__ :
7 fire.Fire(hello)
8 910# from the command line,then run:11python hello.py
# Hello World!12python hello.py --name=David
# Hello David!13python hello.py --help
# Shows usage information.例子二
fire
3 4classCalculator(object): 5"""A simple calculator class.""" 6 7defdouble(self, number): 8return2 * number
910if __name__ ==
__main__ :
11 fire.Fire(Calculator)
1213# from the command line, then run:1415python calculator.py double
10# 2016python calculator.py double --number=
15# 30例子三
fire
3classExample(object): 4defhello(self, name= world ): 5"""Says hello to the specified name.""" 6return Hello {name}! .format(name=name)
7 8defmain(): 9 fire.Fire(Example)
1011if __name__ == __main__ :
12 main()
1314##########################15 当 Fire 函数运行时,我们的命令被执行。
16
仅仅通过调用 Fire,现在我们可以把样本类当作命令行工具来使用。
171819$ ./example.py hello
20Hello world!
2122$ ./example.py hello David
23Hello David!
2425$ ./example.py hello --name=Google
26Hello Google!
每个 Fire CLI 都带有交互模式。
- 运行 CLI 时使用「-interactive」旗标和命令行以及其他已定义的变量来登录 IPython REPL。
- 请务必查看 Python Fire 的文档,从而了解 Fire 更多实用的特征。
因为 Python Fire 十分简单、普遍和强大,我希望能为你的项目提供一个十分有效的库。
英文链接:http://opensource.googleblog.com/2017/03/python-fire-command-line.html
推荐阅读
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。