Reputation: 129
I'm expecting arguments in this format
filname.py -input="a","b","c"
currently, I'm parsing command line parameters by this code
dict(item.split("=") for item in sys.argv[1].split(" "))
is there any better way to read command line arguments. I tried using OptionParser but OptionParser requires key value pairs to be separated by space.
Upvotes: 0
Views: 214
Reputation: 2200
Here's a specific example of accumulating a list via argparse
, which I mentioned in a comment above.
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='append')
>>> args = parser.parse_args("--foo a --foo b --foo c".split())
>>> print(args.foo)
['a', 'b', 'c']
This is not quite as ideal, since this requires the argument name --foo
to be given with each item you want to add to its list.
An alternative would be to read in a string with commas and split them:
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args("--foo a,b,c".split())
>>> args.foo
'a,b,c'
>>> args.foo.split(',')
['a', 'b', 'c']
I suppose this may be an XY problem. What is it exactly that you are attempting to accomplish by having an argument with parameters like this?
After receiving further information (OP's comments), it appears that the key-value reading is vital.
The Tornado project has a custom option-parsing module tornado.options
which assumes values to be given on the command line as key-value pairs like you want.
I would not advise you to import Tornado into your project just to get this to work. However, you can read through the OptionParser
object's definition in that file I linked to see how you might implement such functionality. To simulate argparse
using this new argument parser:
>>> from tornado.options import OptionParser
>>> parser = OptionParser()
>>> parser.define('foo', multiple=True)
>>> parser.parse_command_line('throwaway --foo="a","b","c"'.split())
>>> parser.foo
['"a"', '"b"', '"c"']
Notice that parse_command_line
requires an extra throwaway argument at the beginning. This is because if you don't supply a value, it uses sys.args
and skips the first argument (which is generally the name of the command being executed). In your own parser, you could rewrite this line to start at 0
instead of 1
and avoid this necessity.
Conveniently, Tornado's OptionParser
does include the ability to specify a list through the multiple=True
parameter of define
. You would still have to strip the resulting values of their extraneous quotation marks, but that's done simply enough.
Upvotes: 1