When you encounter a situation that requires a parameter, there are often three ways to do this [1]:
* Direct given
This approach is easy to implement, but slightly less flexible, each time you need to open the source code changes.
* Manual parsing
This method is also more commonly used, but when too many parameters are displayed inconvenient, because each input format and the number of parameters must be a bit. Give a simple example of how this approach is used:
# python code-manually parse parameter
# file name test.py
import sys
if __name__ = = ' __main__ ':
print sys.argv[0]
print ' End "
$python test.py 1
test.py
Automatic parsing
This method is recommended in comparison to the two methods, where the automatic parsing method is more flexible and the parameters are selectable and the order can be indeterminate. It relies mainly on Python package argparse.
The following is mainly about the Python command-line parsing module argpars [2][3]:
1 Introduction
The Argparse module makes user-friendly command line programming more convenient. First you define what parameters are required in your program, and then argparse automatically resolves the previously defined parameters from the SYS.ARGV.
Argparse can also automatically generate help documents and automatically error when the user enters the wrong arguments.
1.1 of a dozen examples
# python code-argparse Example
# code name: prog.py
import argparse
parser = argparse. Argumentparser (description= ' Process some integers. ')
Parser.add_argument (' integers ', metavar= ' N ', type=int, nargs= ' + ',
help= ' An integer for the accumulator ')
Parser.add_argument ('--sum ', dest= ' accumulate ', action= ' store_const ', const=sum, Default=max
,
help= ' sum The integers (default:find the max) '
args = Parser.parse_args ()
print (Args.accumulate (args.integers))
The command line runs the following command to view Help information:
$ python prog.py-h
usage:prog.py [-h] [--sum] n [n ...]
Process some integers.
Positional arguments:
N an integer for the accumulator
optional arguments:-
H,--help Show This help message and exit
--sum sum the integers (default:find the max)
Using the appropriate parameters to run the program, you can get the input parameters of max or sum, if you enter inappropriate parameters, the program will directly error, as follows:
$ python prog.py 1 2 3 4
4
$ python prog.py 1 2 3 4--sum
$ python prog.py a b c
usage:prog.py [H ] [--sum] n [n ...]
prog.py:error:argument n:invalid int value: ' A '
1.1.1 Create an interpreter
>>>parser = Argparse. Argumentparser (description= ' Process some integers. ')
The Argumentparser object stores all the information required to parse the command-line arguments.
1.1.2 Add Parameters
The Add_argument () function enables you to add the required parameters to the Argumentparser object.
These calls tell the Argumentparse how to extract parameters from the command line and convert them to the desired object. This information are stored and used when Parse_args () is called. For example:
>>>parser.add_argument (' integers ', metavar= ' N ', type=int, nargs= ' + ',
help= ' an integer for the Accumulator ')
>>>parser.add_argument ('--sum ', dest= ' accumulate ', action= ' store_const ',
const= Sum, Default=max,
help= ' sum the integers (default:find the max) ')
After the Parse_args () function is called, two objects, integers and accumulate, are returned.
Integers is the number of one or more (list) int;
Accumulate is a sum () function (--sum called), or Max () (--sum not called)
1.1.3 Parsing Parameters
>>> Parser.parse_args (['--sum ', ' 7 ', '-1 ', ', '])
Namespace (accumulate=<built-in function Sum> Integers=[7,-1, 42])
Note: In a script, the Parse_args () function is typically called without arguments, and the arguments are given directly on the command line, and then argumentparser automatically parse the corresponding arguments in SYS.ARGV.
2 Argumentparser Objects
The Argumentparser object is defined as follows:
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)
Each of its parameters is defined as follows:
* Prog-the Name of the program (Default:sys.argv[0])
By default, the Argumentparser object generates the program name in the Help information based on the value of sys.argv[0], excluding the path name.
Usage-the string describing the program usage (default:generated from arguments added to parser)
By default, the Argumentparser object can automatically generate usage information based on parameters
Description-text to display before the argument Help (Default:none)
Description is used to show brief introductory information about a program, usually including: what the program can do and how to do it. Description in Help information between usage information and parameter descriptions
Epilog-text to display after the argument help (Default:none)
Similar to description, additional descriptive information for a program after a parameter description
Parents-a List of Argumentparser objects whose arguments should also be included
Sometimes multiple parsers may have the same set of parameters, to achieve code reuse, we can extract these same parameter sets into a separate parser, specifying the parent parser through parents when creating other parsers, so that the newly created parser contains the same set of parameters.
Formatter_class-a class for customizing the Help output
Help information can be customized via Formatter_class
Prefix_chars-the set of characters that prefix optional arguments (default: '-')
In general, we use '-' as the option prefix, and Argumentparser also supports custom option prefixes through Prefix_chars
Fromfile_prefix_chars-the set of characters that prefix files from which additional arguments should is read (default:n One
Argument_default-the Global default value for arguments (Default:none)
Conflict_handler-the strategy for resolving conflicting optionals (usually unnecessary)
Add_help-add a-h/–help option to the parser (default:true)
Whether to disable the-H–HELP option
* Personally think the commonly used parameters are marked in bold, basically if there is no special need to specify a description on it.
The official website and some references have given each parameter detailed definition and the concrete use method, here does not repeat. *
3 Add_argument () method
Argumentparser.add_argument (name or flags ...) [, Action] [, Nargs] [, Const] [, Default] [, type] [, Choices] [, Required] [, help] [, Metavar] [, Dest])
Each parameter has the following meanings:
* name or flags-either a name or a list of option strings, e.g. Foo Or-f,–foo.
Specifies an optional parameter or positional parameter. Where the optional arguments are-start with the position argument left
action-the Basic type of action to being taken when this argument was encountered at the command line.
Specify how command line arguments are handled
nargs-the Number of command-line arguments that should is consumed.
Specify multiple command-line arguments associated with a arcion, see official documentation
Const-a constant value required by some action and Nargs selections.
Constant value, which is not read from the command line, needs to be specified in some specific action.
default-the Value produced if the argument is absent from the command line.
If the parameter can be default, default specifies the parameter value when the command line parameter does not exist.
type-the type to which the command-line argument should is converted.
By default, the Argumentparser object saves command line arguments as strings. Typically, however, command-line arguments should be interpreted as another type, such as float or int. You can perform type checking and type conversions on command-line arguments by specifying type
choices-a Container of the allowable values for the argument.
Limit the value of a command line argument to a range, and the error will be exceeded
Required-whether or not the command-line option is omitted (Optionals only).
Specifies whether command-line arguments are required, and the default parameters specified by-f–foo are optional.
help-a Brief description of what the argument does.
Help document
Metavar-a name for the argument in usage messages.
Optional parameters for writing help documents
Dest-the name of the attribute to is added to the object returned by Parse_args ().
Dest Allow custom Argumentparser parameter property names
4 Finally, let's take a look at the usage
commonly used parameters are listed, and then use a small example in the Pytorch source code to illustrate the usage:
Parser = Argparse. Argumentparser (description= ' pytorch mnist Example ') parser.add_argument ('--batch-size ', Type=int, default=64, Metavar= ' N ', help= ' input batch size for training (default:64) ') parser.add_argument ('--test-batch-siz E ', Type=int, default=1000, metavar= ' N ', help= ' input batch size for testing (default:1000) ') parser.a Dd_argument ('--epochs ', Type=int, default=10, metavar= ' N ', help= ' number of epochs to train (default:1 0) parser.add_argument ('--lr ', Type=float, default=0.01, metavar= ' LR ', help= ' learning rate ') (default: 0.01) ' parser.add_argument ('--momentum ', Type=float, default=0.5, metavar= ' M ', help= ' SGD momentum (d efault:0.5) ' Parser.add_argument ('--no-cuda ', action= ' store_true ', Default=false, help= ' disables ') CUD A training ') parser.add_argument ('--seed ', Type=int, default=1, metavar= ' S ', help= ' random seed (defaul T:1) Parser.add_argument ('--log-interval ', Type=int, default=10, metavar= ' N ', help= ' How many batches to wait before L ogging training status ') args = Parser.parse_args ()
Reference:
1. Argparse
2. Python command line parsing module Argparse
3. Official Document