相关疑难解决方法(0)

argparse参数嵌套

我在python中有以下代码:

parser = argparse.ArgumentParser(description='Deployment tool')
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', '--add', dest='name_to_add', help='Add a new group or a role to existing group')
group.add_argument('-u', '--upgrade', dest='name_to_upgrade', help='Upgrade a group with the new version')
parser.add_argument('--web_port', help='Port of the WEB instance that is being added to the group')
Run Code Online (Sandbox Code Playgroud)

我的问题是"--web_port"选项.我希望能够仅使用"-a"选项添加此选项,但不能使用"-u"添加此选项.

我希望能够运行:"python my_script.py -a name --web_port = XXXX".

我不想运行:"python my_script.py -u name --web_port = XXXX"

我应该如何更改代码以便能够以这种方式运行它?

谢谢,阿尔沙夫斯基亚历山大.

python argparse

21
推荐指数
1
解决办法
7604
查看次数

如何在argparse互斥组中包含一个位置参数?

我知道,对于一个互相排斥的群体来说,多个位置论证是没有意义的,因为你不能说谁是谁.但我需要在其中包含一个位置参数.

我需要的:

$ myprogram -h
usage: myprogram [-h] [--delete value | --update value | value]
Run Code Online (Sandbox Code Playgroud)

其中position value是默认操作(类型为"--include").(myprogram没有参数也必须有效).

我的第一次尝试(这不起作用):

parser = ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('--delete', metavar='value')
group.add_argument('--update', metavar='value')
group.add_argument('value')
Run Code Online (Sandbox Code Playgroud)

那可能吗?


第二次尝试:

parser = ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('--delete', action='store_true')
group.add_argument('--update', action='store_true')
group.add_argument('--insert', action='store_true', default=True)
group.add_argument('value')
Run Code Online (Sandbox Code Playgroud)

python argparse

6
推荐指数
1
解决办法
2980
查看次数

标签 统计

argparse ×2

python ×2