Python编程编写完善的命令行工具
作者:somenzz 发布时间:2023-08-02 11:22:56
标签:Python,命令行
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 arg_demo2.py double 10 -- --trace
结果如下:
还可以为你生成 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编程编写完善的命令行工具的详细内容!
来源:https://blog.csdn.net/somenzz/article/details/118166073


猜你喜欢
- 在pycharm中设置python脚本的文件模板,让文件创建的时候就自动写上一些相关信息:1、进入pycharm的File->sett
- PHP Warning: strtotime(): It is not safe to rely on the system's t
- Python命名空间和作用域总结emmm,这一块讲了2个内容,一个是命名空间,一个是作用域。一个一个说吧命名空间A namespace is
- 背景自从把我手上的任务全部转换成docker运行和管理之后,遇到了一系列的坑,这次是mysql备份的问题。原因是启动mysql镜像的时候没有
- 当浏览网页时,总有那么一类网站华丽而富有趣味性。在浏览信息的同时,足够让我们眼前一亮。它们在充分融入动画、视频、游戏、甚至是与众不同的交互操
- 如下所示:# 返回一个列表中第二大的数def second(ln):max = 0s = {}for i in range(len(ln))
- 1. 基本介绍tensorflow设备内存管理模块实现了一个best-fit with coalescing算法(后文简称bfc算法)。bf
- 1、800*600下,网页宽度保持在778以内,就不会出现水平滚动条,高度则视版面和内容决定。2、1024*768下,网页宽度保持在1002
- python最值与下标最大值的下标winner = np.argmax(scores)多个最大值的下标(np.argwhere返回数组中非0
- 一.MYSQL的命令行模式的设置桌面->我的电脑->属性->环境变量->新建->PATH=“;path\mys
- template代码:<template> <div class="hello"> <ul
- 前言我们在往期对matplotlib.pyplot()方法学习,到现在我们已经会绘制折线图、柱状图、散点等常规的图表啦(往期的内容如下,大家
- 操作方法:先要安装好SQLServer2005,并且记住安装时自己设置的用户名和密码。下面以恢复SQLServer下备份的数据库文件epdm
- 写在之前SQLite 是一个小型的关系型数据库,它最大的特点在于不需要单独的服务、零配置。我们在之前讲过的两个数据库,不管是 MySQL 还
- html结构如下<div class="row"> <div class="co
- 一个站点成功与否,不是在于所用的程序语言是PHP还是ASP,也不在于用BLOG建站或是CMS建站,内容和专业很重要。博客很好起步,CMS体系
- 2012年,AlexNet横空出世。它首次证明了学习到的特征可以超越手工设计的特征。它一举打破了计算机视觉研究的现状。AlexNet使用了8
- 本文实例讲述了Python实现的远程文件自动打包并下载功能。分享给大家供大家参考,具体如下:一 点睛在Linux系统集群运营当中,时常需要批
- vue-cli-service build 环境设置使用vue-cli3打包项目,通过配置不同的指令给项目设置不一样的配置。npm run
- urllib包和http包都是面向HTTP协议的。其中urllib主要用于处理 URL,使用urllib操作URL可以像使用和打开本地文件一