Python command Module Argparse learning notes (iv)

Source: Internet
Author: User

    • Default parameters
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 '
    • Parameter section uses

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.