我想要:
named
参数传递给 Python 脚本,filter
参数也传递给脚本,arguments
与 filter
(如果提供)、arguments
(匹配 filter
参数(如果提供)) 添加到 array[]
,error message and syntax help
或者只给出了 arguments
参数,则使用 filter
退出(filter
依赖于 - 需要 - 其他 arguments
)。例如:
python script.py
应生成
usage
帮助消息,然后退出。
python script.py --arg string
应将 arg
string
添加到 array[]
。
python script.py --arg string1 --arg string2 --arg string3
应将所有
arguments
添加到 array[]
。
python script.py --arg string1 --arg string2 --arg string3 --filter '*2*'
应该仅将那些与 arguments
filter
添加到 array[]
,因此在这种情况下,它只会将
string2
添加到
array[]
并忽略其余部分。所以:
argument
,
filter
论证,
这是一个示例,但它无法按预期工作,因为我认为 group = parser.add_mutually_exclusive_group(required=True)
import argparse
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='Dependent argument testing')
# Create a mutually exclusive group for the --arg and --filter options
group = parser.add_mutually_exclusive_group(required=True)
# Define the --arg argument (required)
group.add_argument('--arg', type=str, help='Specify the argument')
# Define the --filter argument (optional)
group.add_argument('--filter', type=str, help='Specify the filter (optional)')
# Parse the command-line arguments
args = parser.parse_args()
# Access the values of the arguments
if args.arg:
print(f'Argument: {args.arg}')
if args.filter:
print(f'Filter: {args.filter}')
忘记互斥的群体。
script.py --arg string1 --arg string2 --arg string3 --filter '*2*'
使用“-h/--help”获取自动用法和帮助。在没有给出任何参数的情况下尝试获取使用是可能的,但我认为不值得付出额外的努力。将“--arg”定义为“追加”,您可以根据需要添加任意数量的字符串。
'--filter'可以是默认的'store'。
包括
print(args)
剩下的就是后期解析逻辑和代码了。