Sriram
Sriram

Reputation: 1190

How to parse a custom string using optparse?

How to parse a custom string using optparse, instead of command line argument?

I want to parse a string that I get from using raw_input(). How can I use optparse for that?

Upvotes: 1

Views: 2296

Answers (2)

Jed Smith
Jed Smith

Reputation: 15974

optparse expects a list of values that have been broken up shell-style (which is what argv[1:] is). To accomplish the same starting with a string, try this:

parser = optparse.OptionParser()
# Set up your OptionParser

inp = raw_input("Enter some crap: ")

try: (options, args) = parser.parse_args(shlex.split(inp))
except:
    # Error handling.

The optional argument to parse_args is where you substitute in your converted string.

Be advised that shlex.split can exception, as can parse_args. When you're dealing with input from the user, it's wise to expect both cases.

Upvotes: 9

Nicholas Riley
Nicholas Riley

Reputation: 44341

Use the shlex module to split the input first.

>>> import shlex
>>> shlex.split(raw_input())
this is "a test" of shlex
['this', 'is', 'a test', 'of', 'shlex']

Upvotes: 4

Related Questions