简体   繁体   中英

Tuple of tuples as argparse command line argument

I need users to provide a list of lists of numbers as command line arguments.

The current solution I'm adopting is here below, the question is whether there is a more pythonic or more standard way of doing it.

Currently I'm accepting a comma-separated list of space-separated numbers from command line, like this:

$ python foo.py --numbers '1 2 3, 4 5 6'

and internally I do

def list_of_lists(arg):
    return map(lambda l: map(float, l), map(str.split, a.split(',')))

parser.add_argument('--numbers', type=list_of_lists)

to transform the string "1 2 3, 4 5 6" into [[1,2,3],[4,5,6]] .

What you have is fine. If I were writing it, I'd use commas and semicolons as delimiters (being strict about it: no whitespace allowed), and use a list comprehension for parsing:

def list_of_lists(arg):
    return [float(x.split(',')) for x in arg.split(';')]

but that's really just cosmetic.

The next question is: how much verification do you want to do in list_of_lists ? Right now, this simple version assumes that the string is in exactly the format you want. You can add more logic to catch errors, raising argparse.ArgumentTypeError to signal incorrect values.

Try action="append" and use --numbers more than once.

This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times.

import argparse

def to_list(arg):
    return [int(i) for i in arg.split(",")]

parser = argparse.ArgumentParser()
parser.add_argument("--numbers", action="append", type=to_list)
parsed = parser.parse_args("--numbers 1,2,3 --numbers 4,5,6".split())
print(parsed)

Output:

Namespace(numbers=[[1, 2, 3], [4, 5, 6]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM