Parsing flags in Python

I am trying to manually parse the arguments and flags with a given string.

For example, if I have a line

"--flag1 'this is the argument'"

I expect to return

['--flag1', 'this is the argument']

for any arbitrary number of flags per line.

The difficulty I'm having is figuring out how to handle verbose flag arguments.

For example, if I do ( parser

comes from argparse

)

parser.parse_args("--flag1 'this is the argument'".split())

"--flag1 'this is the argument'".split()"

becomes

['--flag1', "'this", 'is', 'the', "argument'"]

which I don't expect. Is there an easy way to do this?

+3


source to share


1 answer


You're lucky; Is there an easy way to do this. Use shlex.split

. It should split the string the way you want.



>>> import shlex
>>> shlex.split("--flag1 'this is the argument'")
['--flag1', 'this is the argument']

      

+8


source







All Articles