Python:如何在optparse中将选项设置为必填项?
我看过这个链接
但是我不太清楚怎么让optparse中的选项变成必填的?
我试着设置“required=1”,但出现了一个错误:
无效的关键字参数:required
我想让我的脚本要求用户输入--file
这个选项。我知道当你没有给--file
提供值时,action
关键字会报错,因为它的action="store_true"
。
9 个回答
10
在每个必填变量的帮助信息开头,我会写上一个 '[REQUIRED]' 的字符串,这样可以标记它,以便后续处理。然后我可以简单地使用这个函数来把它包裹起来:
def checkRequiredArguments(opts, parser):
missing_options = []
for option in parser.option_list:
if re.match(r'^\[REQUIRED\]', option.help) and eval('opts.' + option.dest) == None:
missing_options.extend(option._long_opts)
if len(missing_options) > 0:
parser.error('Missing REQUIRED parameters: ' + str(missing_options))
parser = OptionParser()
parser.add_option("-s", "--start-date", help="[REQUIRED] Start date")
parser.add_option("-e", "--end-date", dest="endDate", help="[REQUIRED] End date")
(opts, args) = parser.parse_args(['-s', 'some-date'])
checkRequiredArguments(opts, parser)
16
因为 if not x
对某些(负数、零)参数不起作用,
而且为了避免写很多个 if 判断,我更喜欢用这样的方式:
required="host username password".split()
parser = OptionParser()
parser.add_option("-H", '--host', dest='host')
parser.add_option("-U", '--user', dest='username')
parser.add_option("-P", '--pass', dest='password')
parser.add_option("-s", '--ssl', dest='ssl',help="optional usage of ssl")
(options, args) = parser.parse_args()
for r in required:
if options.__dict__[r] is None:
parser.error("parameter %s required"%r)
70
你可以很简单地实现一个必选的选项。
parser = OptionParser(usage='usage: %prog [options] arguments')
parser.add_option('-f', '--file',
dest='filename',
help='foo help')
(options, args) = parser.parse_args()
if not options.filename: # if filename is not given
parser.error('Filename not given')