2020年8月9日 / 765次阅读 / Last Modified 2020年8月9日
argparse模块
首先要搞清楚什么是sub-command?其实,我们每天都在使用的git,就是典型的sub-command命令行。
比如:git add, git push, git rebase......这些命令行中的add,push,rebase都叫做sub-command!(他们可不是固定位置的参数哦,每一个sub-command都有一整套属于自己的其它可选或必选参数)
python自带的argparse模块,也可以让我们实现sub-command的功能。
下面从我的maily小项目中,摘一段代码:
parser = argparse.ArgumentParser(
formatter_class = argparse.RawDescriptionHelpFormatter,
description = VER + textwrap.dedent('''
Usage Examples:
1), inline
$ python3 maily.py inline --subject a_title --content test_content
--to to@qq.com --fromaddr from@qq.com --passwd your_password
--smtp smtp.qq.com
You can also specify -a for attachments.
The default --contype is plain, html is supported.
--cc and --bcc are for other receivers.
The default --port is 587, you can also set it to 25, 465 or others,
with --tlayer option if needed.
One more thing, there three ways to fill the email's content:
(a), fill --content options in cmd line;
(b), $ python3 maily.py ..... < content.txt
(c), $ echo your_content | python3 maily.py ...
help info for inline:
$ python3 maily.py inline -h
'''),
epilog = 'maily project page: '
'https://github.com/xinlin-z/maily\n'
'python note blog: '
'https://www.pynote.net'
)
parser.add_argument('-V', '--version', action='version', version=VER)
subparser = parser.add_subparsers(dest='subcmd',
title='sub commands')
parser_inline = subparser.add_parser('inline',
help='parameters are specified in cmd line, one email sent '
'by each cmd')
parser_infile = subparser.add_parser('infile',
help='parameters are stored in json files, support batch mode')
# subcommand: inline
parser_inline.add_argument('--subject', required=True,
help='subject for this email')
parser_inline.add_argument('--content', default=argparse.SUPPRESS,
help='email content')
...
# subcommand: infile
parser_infile.add_argument('msgfile',
help='msg file in json format')
#
args = parser.parse_args()
以上代码实现了两个sub-command,inline和infile,这两个subcommand后面跟的参数完全不同,用-h查看,它们的-h信息也完全不同。(中间省略很大段代码)
关于sub-command,具体请参考:https://docs.python.org/3/library/argparse.html#sub-commands
测试sub-command,欢迎试用我的maily项目。
-- EOF --
本文链接:https://www.pynote.net/archives/2334
前一篇:用json.tool验证和美化json数据
后一篇:json模块的使用
©Copyright 麦新杰 Since 2019 Python笔记