首页 > 解决方案 > argparse:(x 和 y)或(z)

问题描述

我有以下代码:

def main():
    argParser = argparse.ArgumentParser(description = 'DESCRIPTION',epilog = 'Please see README.MD for guidance on how to use this script')
    argParser.add_argument('-i', '--inFile', action='store',type=str, required = True, help = 'Input config file')
    argParser.add_argument('-o', '--outFile', action = 'store', default = sys.stdout, type = argparse.FileType('w'), required = False, help = 'Output VCD File')
#   generate_config_group = argParser.add_mutually_exclusive_group()
    argParser.add_argument('-g', '--generate-config', action='store_true',help='Generate empty config File to fill')
    args = argParser.parse_args()

    print("\nExecuting Script:" + str(sys.argv[0]))
    print("  config file:" + str(args.inFile))
    print("  vcd outFile:" + str(args.outFile.name))

    if args.generate-config:
        if generate_config():
            return 'config generated. see sample-config.ini. You will need to edit these values for this script to run successfully'

我想要它,这样您要么需要 -i 和 -o 参数,要么需要 -g 参数。现在如果你提供 -g,你仍然会因为你没有提供 -i 和 -o 而生气。这样做的方法是什么?我听说 subparsers 可能是一种方式,但我看到使用这些,你以不同的方式调用命令 - script.py subparser_name -flags

我不想那样。我只想要 -o 和 -i 和 -g 作为可能的标志。

标签: pythonargparse

解决方案


为什么不将 IF 最后更新为:

import warnings
if (args.generate-config) or (args.inFile and args.outFile):
    if generate_config():
        return 'config generated. see sample-config.ini. You will need to edit these values for this script to run successfully'

else:
   warnings.warn("When executing script i and o or g are required.")


推荐阅读