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

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

问题描述

我想要一个带有--action=标志的程序,其中有效选择是dumpupload,其中upload是默认选项.如果(并且仅当)选择了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.

推荐答案

您可以使用 :

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.')

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

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