依赖于 Argparse 的其他参数的参数 [英] Arguments that are dependent on other arguments with Argparse

查看:26
本文介绍了依赖于 Argparse 的其他参数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想完成这样的事情:

-LoadFiles
    -SourceFile "" -DestPath ""
    -SourceFolder "" -DestPath ""
-GenericOperation
    -SpecificOperation -Arga "" -Argb ""
    -OtherOperation -Argc "" -Argb "" -Argc ""

用户应该能够运行以下内容:

A user should be able to run things like:

-LoadFiles -SourceFile "somePath" -DestPath "somePath"

-LoadFiles -SourceFolder "somePath" -DestPath "somePath"

基本上,如果你有-LoadFiles,你需要在之后有-SourceFile-SourceFolder.如果您有-SourceFile,则需要有-DestPath

Basically, if you have -LoadFiles, you are required to have either -SourceFile or -SourceFolder after. If you have -SourceFile, you are required to have -DestPath, etc.

这个其他参数的必需参数链是否可能?如果没有,我至少可以做一些类似的事情,如果你有 -SourceFile,你必须有 -DestPath?

Is this chain of required arguments for other arguments possible? If not, can I at least do something like, if you have -SourceFile, you MUST have -DestPath?

推荐答案

在你创建的 ArgumentParser 实例上调用 parse_args 后,它会给你一个命名空间 对象.只需检查是否存在其中一个参数,那么另一个参数也必须存在.喜欢:

After you call parse_args on the ArgumentParser instance you've created, it'll give you a Namespace object. Simply check that if one of the arguments is present then the other one has to be there too. Like:

args = parser.parse_args()
if ('LoadFiles' in vars(args) and 
    'SourceFolder' not in vars(args) and 
    'SourceFile' not in vars(args)):

    parser.error('The -LoadFiles argument requires the -SourceFolder or -SourceFile')

这篇关于依赖于 Argparse 的其他参数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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