Как бы я обработал argparse для одной или нескольких строк? - PullRequest
0 голосов
/ 21 марта 2019

Я использую argparse, чтобы проверить, является ли мой ввод одной строкой временной метки или несколькими строками временной метки, разделенными запятыми.

Например, ввод может быть либо "xxxx-xx-xx xx:xx:xx.xxx" or "xxxx-xx-xx xx:xx:xx.xxx,xxxx-xx-xx xx:xx:xx.xxx,xxxx-xx-xx xx:xx:xx.xxx,,,,"

Я прохожу:

parser.add_argument("-timestamp", dest="timestamp",required = True, help = "single or multiple timestamp of the format:xxxx-xx-xx xx:xx:xx.xxx, seperated by ',' ", type = is_valid_string(parser, arg))

Вот что я имел в виду, но совершенно не понял, как определить, является ли это одна или несколько строк определенного типа регулярного выражения (xxxx-xx-xx xx: xx: xx.xxx)

def is_valid_string(parser,arg):
    if not isinstance(arg,str):
        parser.error("\n input should be of type(str)")

EDIT:

Следующее решит мою проблему:

 group = parser.add_mutually_exclusive_group(required=True)
 group.add_argument("-t", dest="timestamp", help = "timestamp should be of the format:xxxx-xx-xx xx:xx:xx.xxx", type = lambda x: check_timestamp(parser,x))
 group.add_argument("-T", dest="timestamps", help = "timestamps should be ',' seperated and of the format:xxxx-xx-xx xx:xx:xx.xxx", type = lambda x: is_valid_time_list(parser,x))


def is_valid_string(arg):
    if not isinstance(arg,str):
        raise TypeError("\n input should be of type(str)")

def check_valid_time(parser,arg):
    try:
        datetime.strptime(arg,'%Y-%m-%d %H:%M:%S.%f')
        print (1)
    except ValueError:
        print (2)
        parser.error("timestamp %s is not of valid time format"%(arg))
        return ValueError

def check_timestamp(parser,arg):
    is_valid_string(arg)
    check_valid_time(parser,arg)
    return arg

def is_valid_time_list(parser,arg):
    is_valid_string(arg)
    try:
        time_list = arg.split(',')
        for i in range(len(time_list)):
            print (str(time_list[i]))
            check_valid_time(parser,str(time_list[i]))
    except:
        parser.error("list is invalid input format!")
    return arg

Для следующего формата ввода:

python prog.py -T "2017-12-23 12:00:00.000,2017-12-23 12:00:000"

1 Ответ

0 голосов
/ 21 марта 2019

Оказывается, с помощью add_mutuall_exclusive_group вместе с пользовательскими обработчиками ошибок!

group = parser.add_mutually_exclusive_group(required=True)
 group.add_argument("-t", dest="timestamp", help = "timestamp should be of the format:xxxx-xx-xx xx:xx:xx.xxx", type = lambda x: check_timestamp(parser,x))
 group.add_argument("-T", dest="timestamps", help = "timestamps should be ',' seperated and of the format:xxxx-xx-xx xx:xx:xx.xxx", type = lambda x: is_valid_time_list(parser,x))


def is_valid_string(arg):
    if not isinstance(arg,str):
        raise TypeError("\n input should be of type(str)")

def check_valid_time(parser,arg):
    try:
        datetime.strptime(arg,'%Y-%m-%d %H:%M:%S.%f')
        print (1)
    except ValueError:
        print (2)
        parser.error("timestamp %s is not of valid time format"%(arg))
        return ValueError

def check_timestamp(parser,arg):
    is_valid_string(arg)
    check_valid_time(parser,arg)
    return arg

def is_valid_time_list(parser,arg):
    is_valid_string(arg)
    try:
        time_list = arg.split(',')
        for i in range(len(time_list)):
            print (str(time_list[i]))
            check_valid_time(parser,str(time_list[i]))
    except:
        parser.error("list is invalid input format!")
    return arg
...