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

Is there a way to identify default value given by the argparse function ( I am using mutually exclusive option)

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

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

返回的默认值

现在我需要在程序中用 with 识别参数的值是命令行解析值还是从 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