假设我有一个使用argparse处理命令行参数/选项的程序。下面将打印“帮助”信息:
./myprogram -h
or:
./myprogram --help
但是,如果我不带任何参数运行脚本,它什么都不会做。我想要它做的是在不带参数地调用它时显示用法消息。怎么做呢?
假设我有一个使用argparse处理命令行参数/选项的程序。下面将打印“帮助”信息:
./myprogram -h
or:
./myprogram --help
但是,如果我不带任何参数运行脚本,它什么都不会做。我想要它做的是在不带参数地调用它时显示用法消息。怎么做呢?
当前回答
如果您的命令是用户需要选择某些操作的命令,则使用互斥组required=True。
这是对pd321给出的答案的扩展。
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--batch", action='store', type=int, metavar='pay_id')
group.add_argument("--list", action='store_true')
group.add_argument("--all", action='store_true', help='check all payments')
args=parser.parse_args()
if args.batch:
print('batch {}'.format(args.batch))
if args.list:
print('list')
if args.all:
print('all')
输出:
$ python3 a_test.py 用法:a_test.py [h](——批pay_id | - |列表) A_test.py: error:参数之一——batch——list——all是必需的
这只是基本的帮助。其他的一些答案会给你充分的帮助。但至少你的用户知道他们可以做-h
其他回答
我喜欢让事情尽可能简单,这很有效:
#!/usr/bin/env python3
Description = """Tool description"""
Epilog = """toolname.py -a aflag -b bflag with these combined it does blah"""
arg_parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=Description,
epilog=Epilog,
)
try:
if len(sys.argv) == 1:
arg_parser.print_help()
except Exception as e:
print(e)
这就是我如何开始我的所有工具,因为它总是好的包括一些例子
parser.print_help()
parser.exit()
解析器。Exit方法还接受一个状态(returncode)和一个消息值(包括一个尾随换行符自己!)。
举个固执己见的例子, :)
#!/usr/bin/env python3
""" Example argparser based python file
"""
import argparse
ARGP = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawTextHelpFormatter,
)
ARGP.add_argument('--example', action='store_true', help='Example Argument')
def main(argp=None):
if argp is None:
argp = ARGP.parse_args() # pragma: no cover
if 'soemthing_went_wrong' and not argp.example:
ARGP.print_help()
ARGP.exit(status=64, message="\nSomething went wrong, --example condition was not set\n")
if __name__ == '__main__':
main() # pragma: no cover
示例调用:
$ python3 ~/helloworld.py; echo $? usage: helloworld.py [-h] [--example] Example argparser based python file optional arguments: -h, --help show this help message and exit --example Example Argument Something went wrong, --example condition was not set 64 $ python3 ~/helloworld.py --example; echo $? 0
用nargs设置位置参数,检查位置参数是否为空。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
parser.print_help()
参考Python nargs
对于argparse,你可以使用ArgumentParser.print_usage():
parser.argparse.ArgumentParser()
# parser.add_args here
# sys.argv includes a list of elements starting with the program
if len(sys.argv) < 2:
parser.print_usage()
sys.exit(1)
打印帮助 ArgumentParser.print_usage(文件=没有) 打印关于如何在命令行上调用ArgumentParser的简要描述。如果file为None,则sys。假设是Stdout。
如果你为(sub)解析器关联默认函数,就像在add_subparsers中提到的那样,你可以简单地将它作为默认动作添加:
parser = argparse.ArgumentParser()
parser.set_defaults(func=lambda x: parser.print_usage())
args = parser.parse_args()
args.func(args)
如果由于缺少位置参数而引发异常,则添加try-except。