2

Typically one may simply call optparse's method parse_args without any arguments. If, however, one needs to supply a different argument set than that of sys.argv, if may be passed to parse_args.

But what does one do if one needs to pass a string, not a list to parse_args?

I really need a function that does this:

>>> argument_string = "-a arga -b \"argument b\" arg1 arg2"
>>> parse_arguments(argument_string)"
['-a', 'arga', '-b', 'argument b', 'arg1', 'arg2']

Because

>>> argument_string.split(" ")
['-a', 'arga', '-b', '"argument', 'b"', 'arg1', 'arg2']

doesn't cut it. Any thoughts?

0

2 Answers 2

5

This is what the shlex module is for (well, it's one thing that it's for...):

>>> import shlex
>>> argument_string = "-a arga -b \"argument b\" arg1 arg2"
>>> l = shlex.split(argument_string)
>>> l
['-a', 'arga', '-b', 'argument b', 'arg1', 'arg2']
Sign up to request clarification or add additional context in comments.

Comments

4

Use the shlex module for this:

>>> import shlex
>>> shlex.split("-a arga -b \"argument b\" arg1 arg2")
['-a', 'arga', '-b', 'argument b', 'arg1', 'arg2']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.