How to take two positional arguments when optinal isn't set in argparse

二次信任 提交于 2020-04-16 05:47:10

问题


I want to write a argparse command that needs two postional arguments when I don't set a optional argument. In my case it's like I want to call it with two necessary parameters but when I say python3 test.py -gui I want that you don't need this two arguments, because then you are using the gui.

Thx


回答1:


This is what I was proposing in the comments:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--gui', action='store_true', help="use GUI")
parser.add_argument('args', nargs='*')
cmdargs = parser.parse_args()
nargs = len(cmdargs.args)
nargs_expected = 0 if cmdargs.gui else 2
if nargs != nargs_expected:
    parser.error(f"{nargs_expected} arguments were expected, but got {nargs}")


来源:https://stackoverflow.com/questions/60914777/how-to-take-two-positional-arguments-when-optinal-isnt-set-in-argparse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!