如何使用OptionParser制作自定义命令行界面?

2024-04-29 05:05:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用optparse模块中的OptionParser来解析使用raw_input()获得的命令。在

我有这些问题。在

1.)我使用OptionParser解析这个输入,比如for(获取多个参数)

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

我在add_option()中为“-c”设置action='store_true',现在如果有另一个选项有多个参数,比如-d x y z,那么如何知道哪个参数来自哪个选项?如果其中一个参数需要像

^{pr2}$

2.)如果我想做这样的事。。在

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

现在每个条目都不能影响上一个命令设置的其他选项。如何实现这些目标?在


Tags: 模块命令forinput参数rawfoomy
3条回答

对于第2部分:您需要为每一行处理一个新的OptionParser实例。再看看cmd module来编写这样的命令循环。在

optparse通过要求一个参数始终具有相同数量的parameters(即使该数字为0),不允许使用变量参数参数:

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.

解决#2的方法是不将以前的值重用到^{},因此它将创建一个新的values对象而不是更新。在

也可以使用nargs选项属性求解#1,如下所示:

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

相关问题 更多 >