Python command line parsing module details, python command line details
This article focuses on the Python command line parsing module.
There are two common parser types for Python command lines: getopt module and argparse module. The two parsers are explained below.
Getopt Module
This module can help the script parse command line parameters, usually sys. argv [1:]. It complies with the same conventions of the getopt () function of Unix (use-/-- to specify command parameters ). This module provides two functions (getopt. getopt ()/getopt. gnu_getopt () and one parameter exception (getopt. GetoptError ).
Here we will focus on the getopt. getopt () function.
Function prototype: getopt. getopt (args, options [, long_options])
This function has three parameters:
- Args: the command line parameter to be parsed by the script;
- Options: short options of the command line. If the specified short options need to be followed by parameters, add ":" to the corresponding short options, such as e :;
- Long_options: this parameter is optional. If the specified length option is followed by a parameter, add "=" after the corresponding length option, such as conding =;
If the given command line parameter cannot be parsed, The GetoptError exception will be thrown.
The return value of a function contains two elements:
- The first element is an (option, value) tuples. Option is the resolution parameter, and value is the value of the corresponding parameter;
- The second element is the list of parameters that the script does not need to execute. That is, these parameters are redundant;
Below are several demos:
Short options:
>>> importgetopt>>> args='-a -b -cfoo -d bar a1 a2'.split()>>> args['-a', '-b', '-cfoo', '-d', 'bar', 'a1','a2']>>> optlist, args= getopt.getopt(args,'abc:d:')>>> optlist[('-a', ''), ('-b', ''), ('-c', 'foo'),('-d', 'bar')]>>> args['a1', 'a2']
Long Options:
>>> s='--condition=foo --testing --output-file abc.def -x a1 a2'>>> args= s.split()>>> args['--condition=foo', '--testing','--output-file', 'abc.def', '-x', 'a1', 'a2']>>> optlist, args= getopt.getopt(args,'x', [... 'condition=','output-file=','testing'])>>> optlist[('--condition', 'foo'), ('--testing', ''),('--output-file', 'abc.def'), ('-x', '')]>>> args['a1', 'a2']
Classic application instances in the script:
importgetopt,sys defmain(): try: opts, args = getopt.getopt(sys.argv[1:],"ho:v", ["help","output="]) except getopt.GetoptErroras err: # print help information and exit: printstr(err) # will print something like "option -a not recognized" usage() sys.exit(2) output =None verbose =False for o, a in opts: if o =="-v": verbose =True elif o in ("-h","--help"): usage() sys.exit() elif o in ("-o","--output"): output = a else: assertFalse,"unhandled option" # ... if __name__ =="__main__": main()
Argparse Module
The argparse module makes it easy to write user-friendly command line interfaces. The program only needs to define the required parameters, and argparse will be responsible for parsing these parameters from sys. argv. The argparse module also automatically generates help and usage information and generates an error message when the user assigns invalid parameters to the program.
It generally takes three steps to use the argparse module:
1. Create a parser
The first step to use argparse is to create an ArgumentParser object:
>>> parser= argparse.ArgumentParser()
The ArgumentParser object stores all the information required to parse the command line into a Python data type.
2. Add Parameters
You can call add_argument () to add program parameter information to ArgumentParser. Normally, this information tells ArgumentParser how to receive strings on the command line and convert them into objects. This information is saved and used when parse_args () is called. For example:
>>> parser.add_argument('--name', help='username')>>> parser.add_argument('--pass', help='password ')
Next, the object returned by calling parse_args () will have two attributes: name and pass. The user name and password are respectively stored.
3. parsing Parameters
ArgumentParser parses parameters using the parse_args () method. It checks the command line, converts each parameter to an appropriate type, and takes appropriate actions. In most cases, this means that a simple Namespace object is created for the attributes parsed from the command line.
>>> argments = parser.parse_args(['--name','li','--pass','si'])
In the script,parse_args()
Generally, the call does not contain parameters,ArgumentParser
Accordingsys.argv
Automatically determines the command line parameters.
ArgumentParser object
Class argparse. argumentParser (prog = None, usage = None, description = None, epilog = None, parents = [], formatter_class = argparse. helpFormatter, prefix_chars = '-', fromfile_prefix_chars = None, argument_default = None, conflict_handler = 'error', add_help = True)
Create a new argmentParserr object. All parameters should be passed with keyword parameters. Each parameter is described in detail below, but they are:
- Prog-program name (default: sys. argv [0])
- Useage-string Describing program usage (default: generated from the parser parameter)
- Text before description-parameter help information (default: NULL)
- Epilog-text after parameter help information (default: NULL)
- A list of parents-ArgmentParser objects. The parameters of these objects should be included.
- Ormatter_class-class for customizing help information
- Prefix_chars-Prefix Character Set of the optional parameter (default :'-')
- Fromfile_prefix_chars-Prefix Character Set of the file to be read by additional parameters (default: None)
- Argument_default-global default value of the parameter (default: None)
- Conflict_handler-policy for resolving conflicting optional parameters (usually unnecessary)
- Add_help-Add the-h/-help option to the Parser (default: True)
Add_argument () method
ArgumentParser. add_argument (nameor flags... [, action] [, nargs] [, const] [, default] [, type] [, choices] [, required] [, help] [, metavar] [, dest])
Defines how to parse a command line parameter. Each of the following parameters has their own detailed descriptions. In short, they are:
- Name or flags-name or list of option strings, such as foo,-f, and -- foo.
- Action-the basic action type taken when this parameter is encountered in the command line.
- Nargs-Number of command line parameters to be read.
- Const-the constant value required by certain actions and nargs options.
- Default-if this parameter is not displayed in the command line.
- Type-the type that the command line parameter should be converted.
- Choices-a container of values allowed by the parameter.
- Required-whether the command line option can be omitted (only for optional parameters ).
- Help-Brief description of parameters.
- Metavar-parameter name in the help information.
- Dest-name of the property to be added to the object returned by parse_args.
Summary
The above is all the details about the Python command line parsing module in this article, and I hope to help you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!