Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Optparse list

I'm using the python optparse module in my program, and I'm having trouble finding an easy way to parse an option that contains a list of values.

For example:

--groups one,two,three.  

I'd like to be able to access these values in a list format as options.groups[]. Is there an optparse option to convert comma separated values into a list? Or do I have to do this manually?

like image 330
Daniel Delaney Avatar asked Dec 24 '08 18:12

Daniel Delaney


People also ask

What is Optparse in Python?

optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module. optparse uses a more declarative style of command-line parsing: you create an instance of OptionParser , populate it with options, and parse the command line.


2 Answers

S.Lott's answer has already been accepted, but here's a code sample for the archives:

def foo_callback(option, opt, value, parser):   setattr(parser.values, option.dest, value.split(','))  parser = OptionParser() parser.add_option('-f', '--foo',                   type='string',                   action='callback',                   callback=foo_callback) 
like image 119
Can Berk Güder Avatar answered Sep 20 '22 14:09

Can Berk Güder


Look at option callbacks. Your callback function can parse the value into a list using a basic optarg.split(',')

like image 30
S.Lott Avatar answered Sep 18 '22 14:09

S.Lott