Argumentparser.set_defaults (**kwargs)
Set_defaults () can set default values for some parameters
>>> parser = Argparse. Argumentparser () >>> parser.add_argument (' foo ', type=int) >>> parser.set_defaults (bar=123, baz= ' Test ') >>> Parser.parse_args ([' 456 ']) Namespace (bar=123, baz= ' test ', foo=456)
Default values at the parser level override default values at the parameter level
>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--foo ', default= ' bar ') >>> parser.set_defaults (foo= ' Test ') >>> Parser.parse_args ([]) Namespace (foo= ' test ')
The Get_defaults () method can get the default values set in Add_argument () and Set_defaults ()
>>> parser = Argparse. Argumentparser () >>> parser.add_argument ('--foo ', default= ' bar ') >>> parser.set_defaults (air= ' Test ') >>> parser.get_default (' air ') ' Test ' >>> parser.get_default (' foo ') ' Bar '
If the script uses only a few parameters from the arguments passed, you can use the Parse_known_args () method to pass other arguments to other scripts.
Argumentparser.parse_known_args (Args=none, Namespace=none)
It works very much like Parse_args (), but instead of generating an error when an extra parameter is present, it returns a tuple and list that contains the fill namespace and the remaining argument string
Import Argparseparser = Argparse. Argumentparser () parser.add_argument (' Bar ') parser.add_argument ('-t ', '--thread ') args = Parser.parse_known_args () if Args: print (args)
Run results
Prefix matching rules apply to Parse_known_args ()
Python command Module Argparse learning notes (iv)