python argparse:强制参数序列

python argparse: force argument sequence

我需要force/check将参数序列交给argparse。 我尝试了 "try/except" 方法,但它似乎不起作用。

import argparse

epilog = '''usage example:'''

parser = argparse.ArgumentParser(description="add watchit hosts", epilog=epilog)
parser.add_argument('--add', nargs='*', default="-1", metavar="key 'value'")
args = vars(parser.parse_args())
try:
    args['add'][0] != 'name'
    args['add'][3] != 'desc'
    args['add'][5] != 'ip'
except:
    print "wrong argument sequence, read the help message!"

print args
print args['add'][1]
print args['add'][3]
print args['add'][5]

以下调用应该会引发错误,因为缺少名称。

root@lpgaixmgmtlx01:/root>python argparse_test.py --add desc 'aixbuildhost - buildhost - Test(Linz)' ip '172.17.14.37' nagiostmpl 'Enable without Notification' tsm 'AIXBUILDHOST' witnode 'lvgwatchit01t' loc 'loc_gru' devgrp 'hg_aix_lpar' persgrp 'cg_aix'

{'add': ['desc', 'aixbuildhost - buildhost - Test(Linz)', 'ip', '172.17.14.37', 'nagiostmpl', 'Enable without Notification', 'tsm', 'AIXBUILDHOST', 'witnode', 'lvgwatchit01t', 'loc', 'loc_gru', 'devgrp', 'hg_aix_lpar', 'persgrp', 'cg_aix']}
aixbuildhost - buildhost - Test(Linz)
172.17.14.37
Enable without Notification
...and so on

有什么巧妙的方法来强制参数顺序?

try/except 仅当 try returns 中的代码块出错时才有效。使用您当前尝试应用的方法,最好使用 if + sys.exit:

import sys
if args['add'][0] is not 'name' or args['add'][3] is not 'desc' or args['add'][5] is not 'ip':
    parser.error("Wrong argument sequence!")

示例:

import argparse
import sys

epilog = '''usage example:'''

parser = argparse.ArgumentParser(description="add watchit hosts", epilog=epilog)
parser.add_argument('--add', nargs='*', default="-1", metavar="key 'value'")
args = vars(parser.parse_args())

if args['add'][0] is not 'name' or args['add'][3] is not 'desc' or args['add'][5] is not 'ip':
    parser.error("Wrong argument sequence!")
    # Returns the usage, the error message, and exits (suggested by @hpaulj)

print args
print args['add'][1]
print args['add'][3]
print args['add'][5]