Reputation: 295
For example, if I give
test.py -a SOMETHING 1 2 3
after option parsing, I want two lists:
>> print opt
>> ['-a', 'SOMETHING']
>> print args
>> ['1', '2', '3']
Is it possible to do this using optparse?
Upvotes: 1
Views: 608
Reputation: 19329
Looking at the optparse documentation it seems like you can do this:
import optparse
parser = optparse.OptionParser()
parser.add_option("-a", action="store", type="string", dest="a")
(opt, arg) = parser.parse_args()
print "Opt:", opt
print "Arg:", arg
If I run this using your command line python test.py -a SOMETHING 1, 2, 3
it prints:
Opt: {'a': 'SOMETHING'}
Arg: ['1', '2', '3']
which seems very close to the desired result.
If you really must have the options as a list, you could add something like this to the code above:
o = list()
for k in vars(opt):
o.append(k)
o.append(getattr(opt, k))
print "List Opt:", o
For me this prints:
List Opt: ['a', 'SOMETHING']
Upvotes: 3