Tag:python argparse command line
#!/usr/bin/env python# -*- coding: utf-8 -*-import argparseparser = Argparse. Argumentparser () parser.add_argument ('--address ', nargs = ' * ', default= ' localhost ', help = "Mandatory, the address to connect") parser.add_argument ('-P ', '--port ', type=int, help = "the port to listen on. default is 3868 ", default=3868) parser.add_argument ('--printbody ', action= ' store_true ', default = false, help= "Optional. if print body of response") parser.add_ Argument ('--file ', action = ' store ', dest= ' file ', help = ' default Configuration file ") Args = parser.parse_args () print (" The address is: ", args.address) Print ("The port listened on is:", args.port) if (args.printbody): print ("PrintboDy exist ") else: print (" Printbody not exist ") Print (" Config file: ", args.file)
The program help output is as follows: C:\>python argparse_t.py --helpusage: argparse_t.py [-h] [--address [address [address  [...]] [-p PORT] [--printbody] [--file file]optional arguments: - H, --help show this help  MESSAGE AND EXIT  --ADDRESS [ADDRESS [ADDRESS&NBSP, ...] Mandatory, the address to connect -p port, --port port the port to listen on. default is 3868 --printbody optional. if print body of response --file file Default configuration file execution output; c:\>python argparse _t.py --addres 10.10.10.10 --port 3868 --file config.cfg --printbodythe address is: [' 10.10.10.10 ']the port listened on is: 3868printbody existconfig file: config.cfg
Add_argument () parameter explanation: (1) Nargs: Indicates that the option can be multiple, such as "address [address ...]" displayed in Help for the--address option, and the value of the option is stored in the list (2) Default: Option defaults (3) Type: Types of options, when the input type does not meet the requirements of the times wrong, such as the program specified in the port in the type, when the input character, error entry: Python argparse_t.py--port d,argparse_t.py:error: argument-p/--port:invalid int Value: Output information in ' d ' (4) Help:--help (5) Action store: Default action mode, which stores the value to the specified variable. Store_const: The stored value is specified in the const portion of the parameter and is used to implement non-Boolean command-line flags. Store_true/store_false: boolean switch. You can have 2 parameters corresponding to one variable. Append: Stores the value into the list, which can be reused. Append_const: Stores the value to the list and stores the value specified in the const portion of the parameter. Version output release information and then exit.
This article is from the "Joshua" blog, make sure to keep this source http://joshuazheng.blog.51cto.com/1683820/1828314
Python command-line module Argparse