如何 argparse 一个不同的类型

how to argparse a type that is diffrent

我正在努力使 python main.py --point 0,0 成为参数并抛出一个参数,如果它不遵循像 int, ', ' , 整数

我真的试过在线搜索,发现你可以做到

parser.add_argument('--point',  type=int, metavar='pointneeded',required=True)

但我找不到一种方法让类型先是 int,然后是逗号,然后是 int。

有什么办法还是我应该手动检查?

将可调用函数传递给 type 参数,这将验证字符串。在这里,您可以在 2 个验证选项之间进行选择:

  • 使用正则表达式
  • 使用 map()int。使用此选项,您可以选择 return 数字列表而不是字符串。
import argparse
import re

def comma_separated_int(arg):
    # Validation Option 1: Using regex
    # if re.match(r"^(\d+,)*\d+$", arg) is None:
    #     raise ValueError()

    # Validation Option 2: Using mapping to int
    int_list = list(map(int, arg.split(",")))

    # Response Option 1: If you want to return the string value e.g. "1,2,3"
    # return arg
    # Response Option 2: If you want to return the list[int] value e.g. [1, 2, 3]
    return int_list

parser = argparse.ArgumentParser()
parser.add_argument('--point',  type=comma_separated_int, metavar='pointneeded', required=True)
args = parser.parse_args()

print(args.point)

输出

$ python3 main.py --point 1
[1]
$ python3 main.py --point 12
[12]
$ python3 main.py --point 123
[123]
$ python3 main.py --point 1,2,3
[1, 2, 3]
$ python3 main.py --point 11,22,333
[11, 22, 333]
$ python3 main.py --point 11,2a,333
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: '11,2a,333'
$ python3 main.py --point a
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: 'a'
$ python3 main.py --point abc
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: 'abc'
$ python3 main.py --point 1,
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: '1,'
$ python3 main.py --point ,1
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: ',1'
$ python3 main.py --point 1,,2
usage: main.py [-h] --point pointneeded
main.py: error: argument --point: invalid comma_separated_int value: '1,,2'