Python argparse; if argument 1 not present, how to

2019-07-24 21:32发布

I have 3 arguments in my python script. Two are required for running the script and argument 1 shows only a list of options. I want that if argument 1 is set, that argument 2 and 3 are not required anymore, and if argument 1 is not used, that argument 2 and 3 are required.

The arguments are as follows:

parser = argparse.ArgumentParser()
parser.add_argument("--1", help="list of options", action="store_true", default=False)
parser.add_argument("--2", help="level", required=True)
parser.add_argument("--3", help="folder", required=True)
args = parser.parse_args()

I tried it with the following command:

parser = argparse.ArgumentParser()
parser.add_argument("--1", help="list of options", action="store_true", default=False)
parser.add_argument("--2", help="level)
parser.add_argument("--3", help="folder")
args = parser.parse_args()

if args.1:
    print('list of options')
    sys.exit()
if not args.1:
    parser = argparse.ArgumentParser()
    parser.add_argument("--1", help="list of options", action="store_true", default=False)
    parser.add_argument("--2", help="level", required=True)
    parser.add_argument("--3", help="folder", required=True)

But the problem than is that if the user only set option 2 (or only option 3), that the script continues, instead of having both options 2 and 3 required. Is it possible in Python to first test for option 1 and, if this option is not set, continue to test for option 2 and 3, and set these two as required?

0条回答
登录 后发表回答