Python argparse; if argument 1 not present, how to continue and set required next arguments

本小妞迷上赌 提交于 2019-12-11 09:48:33

问题


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?

来源:https://stackoverflow.com/questions/52946555/python-argparse-if-argument-1-not-present-how-to-continue-and-set-required-nex

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