Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

argparse - 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?

question from:https://stackoverflow.com/questions/9978880/python-argument-parser-list-of-list-or-tuple-of-tuples

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...