Python命令行参数检查默认值或给定值

5 投票
2 回答
2200 浏览
提问于 2025-04-18 15:19

这是我的代码部分:

parser = argparse.ArgumentParser()
parser.add_argument('-a', action='store', dest='xxx', default = 'ABC')
parser.add_argument('-b', action='store', dest='yyy')
parser.add_argument('-c', action='store', dest='zzz')
args = parser.parse_args()

我希望代码能这样工作:

如果给定了b和c,就执行命令2。否则,执行命令1。

如果给了-a这个参数,那么再加上-b或-c就会报错。

我尝试了这样做:

if args.xxx and (args.yyy or args.zzz):
   parser.print_help()
   sys.exit()

但这没有成功,因为'-a'总是有一个默认值,我无法更改它。 我该怎么解决这个问题呢?

2 个回答

2

我会使用:

parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='xxx')
parser.add_argument('-b', dest='yyy')
parser.add_argument('-c', dest='zzz')
args = parser.parse_args()

if args.xxx is None:
    args.xxx = 'ABC'
else:
    if args.zzz is not None or args.yyy is not None:
        parser.error('cannot use "b" or "c" with "a"')
if args.zzz is not None and args.yyy is not None:
     command2()
else:
     command1()

检查一个值是否是 None 是判断这个参数是否被提供的最可靠的方法(虽然用更简单的真值测试也差不多)。在内部,parse_args 会保持一个 seen_actions 的列表,但这个列表对用户是不可见的。在 http://bugs.python.org/issue11588 中,有一个提议想要提供一个测试钩子,这样就可以访问这个列表了。

3

这里有一种方法可以实现:

# If option xxx is not the default, yyy and zzz should not be present.
if args.xxx != 'ABC' and (args.yyy or args.zzz):
   # Print help, exit.

# Options yyy and zzz should both be either present or None.
if (args.yyy is None) != (args.zzz is None):
   # Print help, exit.

# Earn our pay.
if args.yyy is None:
    command2()
else:
    command1()

你也可以考虑一种基于子命令的使用模式,正如用户toine在评论中提到的那样。

撰写回答