Python编程编写完善的命令行工具


Posted in Python onSeptember 15, 2021

1. python-fire

python-fire 是一个三方库,可以将任何 Python 对象变成一个命令行接口。

使用前先 pip install fire 下。

可以把你的函数直接变成命令行接口:

import fire
def hello(name="World"):
  return "Hello %s!" % name
if __name__ == '__main__':
  fire.Fire(hello)

然后在命令行,就可以执行这些命令:

python hello.py  # Hello World!
python hello.py --name=David  # Hello David!
python hello.py --help  # Shows usage information.

也可以把可以把你的类直接变成命令行接口:

import fire
class Calculator(object):
  """A simple calculator class."""
  def double(self, number):
    return 2 * number
if __name__ == '__main__':
  fire.Fire(Calculator)

然后就可以这样执行:

python calculator.py double 10  # 20
python calculator.py double --number=15  # 30

除此之外,还有这样的功能:

执行后自动进入交互模式:

command -- --interactive

比如:

Python编程编写完善的命令行工具

查看执行的调用顺序:

python arg_demo2.py double 10 -- --trace

结果如下:

Python编程编写完善的命令行工具

还可以为你生成 shell 自动补全命令的脚本,真的很贴心:

python arg_demo2.py double 10 -- --completion

2. mando

mando 是一个基于 argparse 的装饰器,可以让你在几秒内编写出一个灵活、可维护的命令行工具。

使用前先 pip install mando 下。

用法:

example.py

from mando import command, main
@command
def echo(text, capitalize=False):
    '''Echo the given text.'''
    if capitalize:
        text = text.upper()
    print(text)
if __name__ == '__main__':
    main()

命令行用法:

$ python example.py -h
usage: example.py [-h] {echo} ...
positional arguments:
  {echo}
    echo      Echo the given text.
optional arguments:
  -h, --help  show this help message and exit
$ python example.py echo -h
usage: example.py echo [-h] [--capitalize] text
Echo the given text.
positional arguments:
  text
optional arguments:
  -h, --help    show this help message and exit
  --capitalize

真实执行结果:

$ python example.py echo spam
spam
$ python example.py echo --capitalize spam
SPAM

再复杂一点的:

from mando import command, main
@command
def push(repository, all=False, dry_run=False, force=False, thin=False):
    '''Update remote refs along with associated objects.
    :param repository: Repository to push to.
    :param --all: Push all refs.
    :param -n, --dry-run: Dry run.
    :param -f, --force: Force updates.
    :param --thin: Use thin pack.'''
     print ('Pushing to {0}. All: {1}, dry run: {2}, force: {3}, thin: {4}'
           .format(repository, all, dry_run, force, thin))
if __name__ == '__main__':
    main()

mando 可以理解 Sphinx 风格的文档字符串中的 :param 参数说明,因此可以显示帮助文档。

$ python git.py push -h
usage: git.py push [-h] [--all] [-n] [-f] [--thin] repository
Update remote refs along with associated objects. 
positional arguments:
  repository     Repository to push to.
optional arguments:
  -h, --help     show this help message and exit
  --all          Push all refs.
  -n, --dry-run  Dry run.
  -f, --force    Force updates.
  --thin         Use thin pack.
 

mando 还可以理解 Python3 的类型提示,因此传错了参数,也会有报错提示:

from mando import command, main
@command
def duplicate(string, times: int):
    '''Duplicate text.
    :param string: The text to duplicate.
    :param times: How many times to duplicate.'''
    print(string * times)
if __name__ == '__main__':
    main()

执行:

$ python3 test.py duplicate "test " 5
test test test test test
$ python3 test.py duplicate "test " foo
usage: test.py duplicate [-h] string times
test.py duplicate: error: argument times: invalid int value: 'foo'

最后的话

本文分享编写建命令行工具的三方库,使用起来非常简单,我也是偶然在 GitHub 搜索到的,写代码前先在 GitHub 上搜一下真的是一个很好的习惯,以上就是Python编程编写完善的命令行工具的详细内容,更多关于Python编写完善的命令行工具的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python-嵌套列表list的全面解析
Jun 08 Python
Python利用Beautiful Soup模块创建对象详解
Mar 27 Python
Python内置函数—vars的具体使用方法
Dec 04 Python
如何使用 Pylint 来规范 Python 代码风格(来自IBM)
Apr 06 Python
如何更改 pandas dataframe 中两列的位置
Dec 27 Python
python+opencv边缘提取与各函数参数解析
Mar 09 Python
python Cartopy的基础使用详解
Nov 01 Python
详解解决jupyter不能使用pytorch的问题
Feb 18 Python
pycharm Tab键设置成4个空格的操作
Feb 26 Python
十个Python自动化常用操作,即拿即用
May 10 Python
Matplotlib绘制混淆矩阵的实现
May 27 Python
关于Numpy之repeat、tile的用法总结
Jun 02 Python
python可视化之颜色映射详解
python的变量和简单数字类型详解
Sep 15 #Python
深入浅析Django MTV模式
python 进阶学习之python装饰器小结
Sep 04 #Python
自动在Windows中运行Python脚本并定时触发功能实现
Sep 04 #Python
关于python爬虫应用urllib库作用分析
解决pycharm下载库时出现Failed to install package的问题
You might like
PHP与Java对比学习日期时间函数
2016/07/03 PHP
Laravel框架路由和控制器的绑定操作方法
2018/06/12 PHP
比较搞笑的js陷阱题
2010/02/07 Javascript
jquery下onpropertychange事件的绑定方法
2010/08/01 Javascript
js中将字符串转换成json的三种方式
2011/01/12 Javascript
html中的input标签的checked属性jquery判断代码
2012/09/19 Javascript
javascript修改图片src的方法
2015/01/27 Javascript
Node.js中child_process实现多进程
2015/02/03 Javascript
详解VueJs异步动态加载块
2017/03/09 Javascript
jQuery实现基本隐藏与显示效果的方法详解
2018/09/05 jQuery
如何使用puppet替换文件中的string
2018/12/06 Javascript
layui自定义ajax左侧三级菜单
2019/07/26 Javascript
Vue组件间的通信pubsub-js实现步骤解析
2020/03/11 Javascript
python启动办公软件进程(word、excel、ppt、以及wps的et、wps、wpp)
2009/04/09 Python
python制作mysql数据迁移脚本
2019/01/01 Python
python 实现提取log文件中的关键句子,并进行统计分析
2019/12/24 Python
Python实现计算图像RGB均值方式
2020/06/04 Python
基于 Python 实践感知器分类算法
2021/01/07 Python
使用简单的CSS3属性实现炫酷读者墙效果
2014/01/08 HTML / CSS
Senreve官网:美国旧金山的奢侈手袋品牌
2019/03/21 全球购物
Hotels.com印度:酒店预订
2019/05/11 全球购物
What is the purpose of Void class? Void类的作用是什么?
2016/10/31 面试题
阿里巴巴Oracle DBA笔试题答案-备份恢复类
2013/11/20 面试题
System.Array.CopyTo()和System.Array.Clone()有什么区别
2016/06/20 面试题
工程项目建议书范文
2014/03/12 职场文书
小学教师师德承诺书
2014/05/23 职场文书
妈妈活动方案
2014/08/15 职场文书
2014年乡镇人大工作总结
2014/11/25 职场文书
2015年计生工作总结范文
2015/04/24 职场文书
2015年大学生党员承诺书
2015/04/27 职场文书
小兵张嘎观后感300字
2015/06/03 职场文书
幼儿园开学家长寄语(2016秋季)
2015/12/03 职场文书
Appium中scroll和drag_and_drop根据元素位置滑动
2022/02/15 Python
Go并发4种方法简明讲解
2022/04/06 Golang
如何使用python包中的sched事件调度器
2022/04/30 Python
使用Nginx的访问日志统计PV与UV
2022/05/06 Servers