Conditional argparse with choice option

空扰寡人 提交于 2019-12-05 19:35:30

Decouple argument parsing from your requirements.

parser.add_argument('--Type', choices=['a','b','c'], required=True)
parser.add_argument('--Input', action='store_true')
parser.add_argument('--Directory', action='store_true')

args = parser.parse_args()

if args.Directory and args.Type != 'c' and not args.input:
    raise argparse.ArgumentError("--Directory requires --Type c and --Input")

(Note that action='store_true' automatically sets type=bool and default=False.)

I would not use the required parameter for either of those things, it is kind of error-prone and not very readable. Just check the validity of the arguments after parsing.

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--Type', type=str, choices=['a','b','c'], help='Options include: a,b,c.', required=True)
    parser.add_argument('--Input', default=False, help='Generate input files', required=False)
    parser.add_argument('--Directory', default=False, help='Secondary directory', required=False)
    parsed_args = parser.parse_args()
    if parsed_args.Directory and not (parsed_args.Input and parsed_args.Type == 'c'):
        parser.error('option --Directory requires --Input and --Type c.')

It's not the prettiest, but you could look up the argument next to --Type and check that that is equal to 'c' like so:

parser.add_argument('--Directory', default=False, help='secondary directory',
                    required=('--Type' in sys.argv and
                              sys.argv[sys.argv.index('--Type') + 1] == 'c')
                   )

I think it is also possible to do something like this

import sys

# Your past code here

args = parser.parse_args()

type = args.Type
input = args.Input
directory = args.Directory

if directory:
    if input != 'c':
        print 'error in argument'
        sys.exit(1)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!