在混合使用位置参数、可选参数和 argparse.REMAINDER
时,我遇到了一个问题。
parser = argparse.ArgumentParser()
parser.add_argument('verbose', action="store")
parser.add_argument('--config', '-c', nargs="?", dest="config_file")
parser.add_argument('--dry-run', action="store_true", dest="dryrun")
parser.add_argument('args', nargs=argparse.REMAINDER, action="store")
示例运行:
python test.py verbose="5" --config config.xml graph --dry-run
预期输出:
verbose = "5"
config_file = config.xml
dryrun = True
args = ['graph']
实际输出:
verbose = "5"
config_file = config.xml
dryrun = False
args = ['graph', '--dry-run']
我的要求是我有verbose
、-c
、--config
和--dry-run
作为命令行选项,而在命令行提供的任何其他选项都应存储在args
列表中,而不管它们在命令行参数中出现的顺序如何。
请帮我看看哪里做错了。
此外,还有没有更好的Python命令行解析器?