开发者

How to parse a custom string using optparse?

开发者 https://www.devze.com 2022-12-11 01:07 出处:网络
How to parse a custom string using optparse, instead of command line argument? I want to parse a string that I get from us开发者_运维技巧ing raw_input().

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

I want to parse a string that I get from us开发者_运维技巧ing raw_input(). How can I use optparse for that?


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.


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']
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号