1

如何使用 optparse 而不是命令行参数解析自定义字符串?

我想解析一个我从使用中得到的字符串raw_input()。我该如何使用 optparse 呢?

4

2 回答 2

9

optparse需要一个已被分解的 shell 样式的值列表(就是这样argv[1:])。要以字符串开头完成相同的操作,请尝试以下操作:

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.

可选参数parse_args是您在转换后的字符串中替换的位置。

请注意,shlex.split可以例外,因为可以parse_args。当您处理来自用户的输入时,明智的做法是期待这两种情况。

于 2009-11-08T20:14:32.400 回答
4

首先使用shlex 模块拆分输入。

>>> import shlex
>>> shlex.split(raw_input())
this is "a test" of shlex
['this', 'is', 'a test', 'of', 'shlex']
于 2009-11-08T20:13:10.733 回答