Argparse 在参数上使用 OR 逻辑

Argparse with OR logic on arguments

我正在为我的脚本编写参数解析器:

import argparse

parser = argparse.ArgumentParser(description='My parser.')
parser.add_argument('path',
                    type=str)
parser.add_argument('-a', 
                    '--all',
                    action='store_true')
parser.add_argument('-t', 
                    '--type',
                    type=str)
parser.add_argument('-d', 
                    '--date',
                    type=str)

这是我要实现的逻辑:

命令看起来像这样:

python myscript.py mypath [-a] OR [-t mytype -d mydate] 

我该如何实现这个逻辑?

你可以这样做:

from argparse import ArgumentParser

parser = ArgumentParser(description='My parser.')

parser.add_argument('path',
                    type=str)
parser.add_argument('-a', 
                    '--all',
                    action='store_true')
parser.add_argument('-t', 
                    '--type',
                    type=str)
parser.add_argument('-d', 
                    '--date',
                    type=str)

args = parser.parse_args()

if args.all:
    print('all argument flow')
else: 
    if not args.type or not args.date:
        print('you need to put either all or specify both type and date')
    else:
        print(args.type, args.date)

print('and',args.path)