python - 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 作为可能的标志。
解决方案
为什么不将 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.")
推荐阅读
- react-native - 在对 GoogleVisionBarcodes 的原生相机做出反应时检测到无法在 IOS 上运行
- reactjs - 我正在尝试使卡居中,但它不起作用
- perl - Faster way to do this comparison of string in perl for foreign charsets
- reactjs - CRA 在 netlify 上构建失败但不是在本地,找不到本地方法的模块?
- button - 如何通过按钮调用 FORM VIEW?(Odoo 13 企业版)
- javascript - 如何根据结束日期显示组数据?
- c - 如何将 C 代码与 Dart 代码静态链接以使用 dart ffi 库启用 ffi
- javascript - React Js - 无法在输入字段中输入值
- excel - 如何使用基于自定义数字格式的 countif
- testing - 赛普拉斯抛出 SyntaxError: 'import' 和 'export' 可能只出现在 'sourceType: module' (17:0)