gpt4 book ai didi

python - 有没有办法识别 argparse 函数给出的默认值(我使用互斥选项)

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:04 24 4
gpt4 key购买 nike

现在,我已经使用 argparse/configargparse 模块为命令行参数的某些参数使用了mutual_exclusive 选项的默认值。

这里的问题是,如果我在命令行上传递一个值,我 argparse/configargparse 会获取参数的值。但是,当我不在命令行中传递值时,参数会获取 argparse/configargparse 返回的默认值。

现在我需要在程序中识别参数的值是命令行解析值还是从 argparse/configargparse 分配的默认值。

下面是使用答案之一提供的建议的示例代码。当我运行下面的代码时

Case 1: python <file.py> --replace. 
I am passing from command line.
so the if loop where i set the default value is not

被执行

    Case 2: python file.py
I am not passing any argument here.
By default "False" is set for "args.replace" and it doesn't go inside the if loop condition where I am setting up the default value.

"Code"

from argparse import ArgumentParser


if __name__ == "__main__":
myarg_sentinel = object()
myarg_default = "True" # The real default

myarg_sentinel_1 = object()
myarg_default_1 = "True" # The real default

p = ArgumentParser()
p.add_argument('--myarg', default=myarg_sentinel)
replace_parser = p.add_mutually_exclusive_group()

replace_parser.add_argument(
'--replace', help='Replace during import',
dest='replace', action='store_true')
replace_parser.add_argument(
'--no-replace', help='Do not replace import',
dest='replace', action='store_false', default=myarg_sentinel_1)

args = p.parse_args()
if args.myarg is myarg_sentinel:
print "----I am setting default val here."
args.myarg = myarg_default

print args.replace

if args.replace is myarg_sentinel_1:
print "I am setting default val here.----"
args.replace = myarg_default_1
print args.myarg, args.replace

最佳答案

创建一个唯一的哨兵值作为默认值,然后将实际收到的值与哨兵值进行比较。

myarg_sentinel = object()
myarg_default = ... # The real default
p = ArgumentParser()
p.add_argument('--myarg', default=myarg_sentinel)
args = p.parse_args()
if args.myarg is myarg_sentinel:
# Option not specified on the command line
args.myarg = myarg_default

关于python - 有没有办法识别 argparse 函数给出的默认值(我使用互斥选项),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44289771/

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