Conditional argparse with choice option

蓝咒 提交于 2019-12-07 14:42:39

问题


Below are three arguments I am writing in a module.

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='--Input' in sys.argv)

The --Type is possible with three options: a,b,c.

Currently, I have it set up so that, if --Directory is true, it requires --Input to be true.

However, I would like add an additional condition to --Directory to require --Type to be == 'c'.

How do I alter the required option in the --Directory argument so that it needs both --Input and --Type == 'c'?


回答1:


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.)




回答2:


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.')



回答3:


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')
                   )



回答4:


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)


来源:https://stackoverflow.com/questions/55595539/conditional-argparse-with-choice-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!