【问题标题】:Argparse with OR logic on arguments在参数上使用 OR 逻辑的 Argparse
【发布时间】:2021-12-30 04:02:51
【问题描述】:

我正在为我的脚本编写一个参数解析器:

import argparse

parser = argparse.ArgumentParser(description='My parser.')
parser.add_argument('path',
                    type=str)
parser.add_argument('-a', 
                    '--all',
                    action='store_true')
parser.add_argument('-t', 
                    '--type',
                    type=str)
parser.add_argument('-d', 
                    '--date',
                    type=str)

这是我要实现的逻辑:

  • path: 必须始终提供。
  • --all:如果提供了,--type--date不应该出现。
  • --type--date:只有在未引入 --all 标志时才必须提供。

命令看起来像这样:

python myscript.py mypath [-a] OR [-t mytype -d mydate] 

我该如何实现这个逻辑?

【问题讨论】:

  • 您是在谈论仅在写入 --all 时才使用 --all 的逻辑还是正确打印使用消息? docs.python.org/3/library/argparse.html#usage
  • 关于如何实现使用--all OR --type mytype --date mydate @mama 之一的逻辑
  • argparse 提供了一个 xor,但它是平的 - 没有任何/所有的组。

标签: python argparse


【解决方案1】:

你可以这样做:

from argparse import ArgumentParser

parser = ArgumentParser(description='My parser.')

parser.add_argument('path',
                    type=str)
parser.add_argument('-a', 
                    '--all',
                    action='store_true')
parser.add_argument('-t', 
                    '--type',
                    type=str)
parser.add_argument('-d', 
                    '--date',
                    type=str)

args = parser.parse_args()

if args.all:
    print('all argument flow')
else: 
    if not args.type or not args.date:
        print('you need to put either all or specify both type and date')
    else:
        print(args.type, args.date)

print('and',args.path)

【讨论】:

  • 这肯定是一种硬编码方式,但我一直在寻找使用 argsparse 本机参数和模块的选项。这样,库将负责打印消息,帮助用户使用正确的格式和逻辑。
  • print 可以替换为parser.error(your_message),以获取消息的使用情况。但是在初始化解析器时,您必须提供自己的usage,使用您希望传达逻辑的任何符号。 argparse 只能实现简单的互斥组逻辑。
  • @Luiscri 如果库会处理这种逻辑,那么它会变得臃肿。 - 你必须自己做:D
猜你喜欢
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 2017-12-06
  • 2013-10-15
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 2011-03-17
相关资源
最近更新 更多