Search code examples
pythonoptparse

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?


Solution

  • 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.