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

use*_*048 5 python command-line-arguments argparse

这是我的代码部分:

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()
Run Code Online (Sandbox Code Playgroud)

我希望代码像这样工作:

如果给出了 b 和 c,则执行 command2。否则,执行命令1

如果给出 -a 参数,则添加 -b 或 -c 会引发错误

我尝试了这样的方法:

if args.xxx and (args.yyy or args.zzz):
   parser.print_help()
   sys.exit()
Run Code Online (Sandbox Code Playgroud)

但它不起作用,因为“-a”始终具有默认值,我无法更改它。我该如何修复它?

FMc*_*FMc 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()
Run Code Online (Sandbox Code Playgroud)

您还可以考虑基于子命令的使用模式,如用户 toine 的评论中所述。