开发者

How to make a custom command line interface using OptionParser?

I am using the OptionParser from optparse module to parse my command that I get using the raw_input().

I have these questions.

1.) I use OptionParser to parse this input开发者_如何转开发, say for eg. (getting multiple args)

my prompt> -a foo -b bar -c spam eggs 

I did this with setting the action='store_true' in add_option() for '-c',now if there is another option with multiple argument say -d x y z then how to know which arguments come from which option? also if one of the arguments has to be parsed again like

my prompt> -a foo -b bar -c spam '-f anotheroption'

2.) if i wanted to do something like this..

my prompt> -a foo -b bar 
my prompt> -c spam eggs 
my prompt> -d x y z 

now each entry must not affect the other options set by the previous command. how to accomplish these?


For part 2: you want a new OptionParser instance for each line you process. And look at the cmd module for writing a command loop like this.


You can also solve #1 using the nargs option attribute as follows:

parser = OptionParser()
parser.add_option("-c", "", nargs=2)
parser.add_option("-d", "", nargs=3)


optparse solves #1 by requiring that an argument always have the same number of parameters (even if that number is 0), variable-parameter arguments are not allowed:

Typically, a given option either takes an argument or it doesn’t. Lots of people want an “optional option arguments” feature, meaning that some options will take an argument if they see it, and won’t if they don’t. This is somewhat controversial, because it makes parsing ambiguous: if "-a" takes an optional argument and "-b" is another option entirely, how do we interpret "-ab"? Because of this ambiguity, optparse does not support this feature.

You would solve #2 by not reusing the previous values to parse_args, so it would create a new values object rather than update.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜