使用Python的optparse模块,如何创建一个带有可变数量参数的选项? [英] With Python's optparse module, how do you create an option that takes a variable number of arguments?
问题描述
使用Perl的Getopt::Long
,您可以轻松定义带有可变数量参数的命令行选项:
With Perl's Getopt::Long
you can easily define command-line options that take a variable number of arguments:
foo.pl --files a.txt --verbose
foo.pl --files a.txt b.txt c.txt --verbose
有没有一种方法可以直接使用Python的optparse
模块执行此操作?据我所知,nargs
选项属性可用于指定固定数量的选项参数,而且我在文档中还没有看到其他选择.
Is there a way to do this directly with Python's optparse
module? As far as I can tell, the nargs
option attribute can be used to specify a fixed number of option arguments, and I have not seen other alternatives in the documentation.
推荐答案
我相信optparse
不支持您的要求(不直接支持-如您所注意到的,如果您愿意做所有回调的额外工作!-).您也可以使用第三方扩展程序 argparse 最简单地做到这一点,该扩展名支持可变数字的参数(并且还增加了其他一些方便的功能).
I believe optparse
does not support what you require (not directly -- as you noticed, you can do it if you're willing to do all the extra work of a callback!-). You could also do it most simply with the third-party extension argparse, which does support variable numbers of arguments (and also adds several other handy bits of functionality).
此URL 记录了argparse
的nargs='*'
可使该选项接受零个或多个参数,'+'
允许其接受一个或多个参数,等等.
This URL documents argparse
's add_argument
-- passing nargs='*'
lets the option take zero or more arguments, '+'
lets it take one or more arguments, etc.
这篇关于使用Python的optparse模块,如何创建一个带有可变数量参数的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!