在python中检查彼此参数的最佳合法方法

时间:2015-08-05 12:52:09

标签: python command-line-arguments

我想说在python中不要使用例如' -a'用' -b'切换。我怎么能在python中做到这一点?

opts, args = getopt.getopt(sys.argv[1:], 'a:b:')
for opt, arg in opts:
    if opt == '-a':
        after = str(arg)
    elif opt == '-b':
        before = int(arg)

例如:

# python script.py -a aaa -b bbb
  don't use -b arg with -a

1 个答案:

答案 0 :(得分:0)

怎么样

mut_exc_opts = ['-a','-b']
opts_only = map(lambda (opt,arg): opt, opts)
matches = [x for x in mut_exc_opts if x in opts_only]
if len(matches) > 1:
    print "do not use options", ', '.join(mut_exc_opts), "together"

适用于任意数量的选项以及必须互斥的任何选项组合。

在python 2.7上测试