Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argument parser list of list or tuple of tuples

I'm trying to use argument parser to parse a 3D coordinate so I can use

--cord 1,2,3 2,4,6 3,6,9 

and get

((1,2,3),(2,4,6),(3,6,9)) 

My attempt is

import argparse parser = argparse.ArgumentParser() parser.add_argument('--cord', help="Coordinate", dest="cord", type=tuple, nargs=3) args = parser.parse_args(["--cord","1,2,3","2,4,6","3,6,9"])  vars(args)  {'cord': [('1', ',', '2', ',', '3'),   ('2', ',', '4', ',', '6'),   ('3', ',', '6', ',', '9')]} 

What would the replacement of the comma be?

like image 989
joedborg Avatar asked Apr 02 '12 15:04

joedborg


1 Answers

You can add your own type. This also allows for additional validations, for example:

def coords(s):     try:         x, y, z = map(int, s.split(','))         return x, y, z     except:         raise argparse.ArgumentTypeError("Coordinates must be x,y,z")   parser.add_argument('--cord', help="Coordinate", dest="cord", type=coords, nargs=3) 
like image 82
georg Avatar answered Oct 06 '22 06:10

georg