如何使用python argpar实现嵌套的可选参数

2024-04-25 18:09:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用一个工具来登录我的服务器: myLogin[-h][--ip[Address]][UserName][Password]

  1. 当不使用--ip时,工具将使用URL名称(我的.server.net)用于连接。在
  2. 当使用--ip但未提供地址时,工具将使用默认ip地址(192.168.1.1)进行连接。在
  3. 如果没有--ip开关,则无法提供地址。在
  4. UserNamePassword是可选的,具有内置的默认值。在

如何使用python argparse库实现依赖关系为[--ip[Address]]的嵌套可选参数?在

我尝试使用add_subparser和add_argument_group,但没有任何运气。在


Tags: 工具ip服务器名称addurlnetserver
1条回答
网友
1楼 · 发布于 2024-04-25 18:09:49
nargs='?'

nargs是否可以设置为?在

'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced. Some examples to illustrate this:

在您的例子中,您使用了一个可选参数,因此当没有提供地址时,将使用const中的值。如果参数完全丢失,则使用default中的值。例如

^{pr2}$

相关问题 更多 >