gpt4 book ai didi

python - argparse:如果设置了标志,则忽略位置参数?

转载 作者:行者123 更新时间:2023-12-02 19:36:28 27 4
gpt4 key购买 nike

我想为命令提供 3 个参数:<version> , <input file><output file>正常使用下。除了有一个特定的标志 --init ,这将基本上运行该程序,而无需任何输入和输出文件规范。

因此,理想情况下,我会使用一个命令:

py program.py --init

py program.py <version> <input file> <output file>

但是,由于始终需要位置参数(因为在除 --init 之外的任何其他情况下都需要所有 3 个参数),似乎没有办法清楚地获得此语法,我所能想到的就是使 3位置参数转换为可选标志,如果在 --init 时可选标志不存在,则引发异常没有被调用。这一切看起来都很丑陋。

到目前为止我的代码:

def get_args():
parser = argparse.ArgumentParser(description="Tool for FOO-ing a BAR.")
parser.add_argument(dest="version", help="The version.")
parser.add_argument(dest="input", help="The input file.")
parser.add_argument(dest="output", help="The output file.")

parser.add_argument("-i", "--init", dest="init", action="store_true", help="Foo Init.")

return parser.parse_args()

澄清:
必须指定所有 3 个参数 ( <version> <input> <output>)。
或者
该程序仅使用 --init 运行应指定标志和 0 个参数。

程序不应接受指定的 0、1 或 2 个参数(没有 --init 标志)。

最佳答案

您可以定义自己的操作类:

class init_action(argparse.Action):
def __init__(self, option_strings, dest, **kwargs):
return super().__init__(option_strings, dest, nargs=0, default=argparse.SUPPRESS, **kwargs)

def __call__(self, parser, namespace, values, option_string, **kwargs):
# Do whatever should be done here
parser.exit()

def get_args():
parser = argparse.ArgumentParser(description="Tool for FOO-ing a BAR.")
parser.add_argument(dest="version", help="The version.")
parser.add_argument(dest="input", help="The input file.")
parser.add_argument(dest="output", help="The output file.")

parser.add_argument("-i", "--init", action=init_action, help="Foo Init.")

return parser.parse_args()

关于python - argparse:如果设置了标志,则忽略位置参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60979532/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com