Python argparse:具有可选和位置参数的互斥参数 [英] Python argparse : mutually exclusive arguments with optional and positional argument

查看:223
本文介绍了Python argparse:具有可选和位置参数的互斥参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过argparse库获取此信息:

I would like to get this with argparse library :

PROG --yesterday | begin-date [end-date]

我尝试将互斥和论点组合在一起,但没有成功.

I tried to combine mutual exclusion and argument groups but I didn't succeed.

该程序仅应接受:

PROG --yesterday
PROG 2015-11-12
PROG 2015-11-12 2015-11-15

是否可以使用argparse做到这一点?

Is it possible to do this with argparse ?

感谢 hpaulj .查看最终结果:

import argparse
from datetime import datetime
import pytz


def argument_date(str_date):
    try:
        return datetime.strptime(str_date, "%Y-%m-%d").replace(tzinfo=pytz.utc)
    except ValueError as e:
        raise argparse.ArgumentTypeError(e)

parser = argparse.ArgumentParser(prog='PROG')
parser.usage = """PROG [-h] [--yesterday | start [end]]"""
parser.add_argument('start', type=argument_date, nargs='?', help='Start date (format YYYY-MM-DD)')
parser.add_argument('end', type=argument_date, nargs='?', help='End date (format YYYY-MM-DD)')
parser.add_argument('--yesterday', action='store_true', help='Only yesterday')

args = parser.parse_args()

if args.yesterday and args.start:
    raise parser.error("--yesterday option is not incompatible with start argument")

if not args.yesterday and not args.start:
    raise parser.error("--yesterday option or start argument should be filled")

if args.end and (args.start >= args.end):
    raise parser.error("end argument should be granter than start")

推荐答案

您最好的选择是在解析后测试值,如果需要,请提供自己的自定义usage.

Your best choice is to test values after parsing, and if needed, provide your own custom usage.

互斥"组可以使用一个可选的位置,例如

A mutually_exclusive_group can work with one optional positional, e.g.

group = parser.add_mutually_exclusive_group()
group.add_argument('-y','--yesterday', action='store_true')
group.add_argument('dates',nargs='?')

我以为它可以与nargs='*'一起使用,但出现ValueError: mutually exclusive arguments must be optional错误.

I was thinking it would work with nargs='*', but I get ValueError: mutually exclusive arguments must be optional error.

因此,一个可选的位置值有效,但是无法将此测试与2个可选的位置值一起使用.

So one optional positional value works, but there's no way of using this test with 2 optional positional values.

parser.add_argument('--yesterday',action='store_true')
parser.add_argument('start',nargs='?')
parser.add_argument('end',nargs='?')

,然后测试args.yesterdayargs.start is Noneargs.end is None.如果这些组合的某些组合有误,请提出parser.error('....').

And then test for args.yesterday, args.start is None and args.end is None. If some combination of those is wrong, then raise parser.error('....').

只要您可以区分默认值和用户给定的值,解析后的测试与您可能强制解析器执行的任何操作一样好.

As long as you can distinguish between the default values and the user given ones, testing after parsing is just as good as anything that you might force the parser to do.

考虑哪种使用消息对您的用户有意义也是一个好主意.例如

It is also a good idea to think about what usage message makes sense to your users. e.g.

例如:

PROG  [--yesterday | [start [end]]]

不是argparse可以自动生成的东西.

is not something that argparse can generate automatically.

这篇关于Python argparse:具有可选和位置参数的互斥参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆