Python 中使用 argparse 的条件命令行参数 [英] Conditional command line arguments in Python using argparse

查看:34
本文介绍了Python 中使用 argparse 的条件命令行参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个带有 --action= 标志的程序,其中有效的选择是 dumpuploadupload 是默认设置.如果(且仅当)dump 被选中,我希望还有一个 --dump-format= 选项.有没有办法使用 argparse 来表达这一点,或者我是否需要只接受所有参数并自己做逻辑.

I'd like to have a program that takes a --action= flag, where the valid choices are dump and upload, with upload being the default. If (and only if) dump is selected, I'd like there to also be a --dump-format= option. Is there a way to express this using argparse, or do I need to just accept all the arguments and do the logic myself.

推荐答案

你可以使用 parser.error:

You could use parser.error:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--action', choices=['upload', 'dump'], default='dump')
parser.add_argument('--dump-format')
args = parser.parse_args()
if args.action != 'dump' and args.dump_format:
    parser.error('--dump-format can only be set when --action=dump.')

这篇关于Python 中使用 argparse 的条件命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆