Python optparse Values Instance
Asked Answered
G

1

53

How can I take the opt result of

opt, args = parser.parse_args()

and place it in a dict? Python calls opt a "Values Instance" and I can't find any way to turn a Values Instance into a list or dict. One can't copy items from opt in this way,

for i in opt:
 myDict[i] = opt[i]

instead, its a clumsy,

myDict[parm1] = opt.parm1
myDict[parm2] = opt.parm2

which implies that every time I add an option, I have to update this code as well; there should be a way to let this take care of itself.

Gratia answered 18/11, 2009 at 3:31 Comment(0)
D
94
options, args = parser.parse_args()
option_dict = vars(options)

(Source is this python-ideas post.)

Dasi answered 18/11, 2009 at 3:34 Comment(4)
Nice. I wasted 5 hours on that.Gratia
I have no clue how, after 12+ years of python, I didn't know about vars(). You learn something new all the time.Gag
@Doctor - 12 years ago we didnt have stackoverflowGillian
12 years and it's the first time I've ever really used vars()Clockwork

© 2022 - 2024 — McMap. All rights reserved.