Optional parameters for action in Argparse

1 default is not set

import argparse
 
parser = argparse.ArgumentParser()
 
parser.add_argument(
        "--relaxation", '-r', action="store_false", 
    )

parser.add_argument(
        "--save_outputs", '-s', action="store_true", 
    )
args = parser.parse_args()
print(args)

(1) Execute without parameters: python test.py The result is:

Namespace(relaxation=True, save_outputs=False)

action="store_false, the default value is True.
action="store_true, the default value is False.

(2) execute python test.py -r -s with parameters, the result is:

Namespace(relaxation=False, save_outputs=True)

action="store_false, it will be False only after manually specifying this parameter.
action="store_true, it will be True only after manually specifying this parameter.

2 set default

import argparse
 
parser = argparse.ArgumentParser()
 
parser.add_argument(
        "--relaxation", '-r', action="store_false", default=False,
    )

parser.add_argument(
        "--save_outputs", '-s', action="store_true", default=True,
    )

args = parser.parse_args()
print(args)

(1) Execute without parameters: python test.py The result is:

Namespace(relaxation=False, save_outputs=True)

The default value is taken by default.
(2) execute python test.py -r -s with parameters, the result is:

Namespace(relaxation=False, save_outputs=True)

Get the value in action.

3 Summary

The priority of default is higher than that of inactive actions, and the priority of activated actions is higher than that of default. That is: the value of default has priority over the value of default, and the value of action has priority over the value of action attribute.

Guess you like

Origin blog.csdn.net/weixin_50008473/article/details/132181997