In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use argparser". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use argparser.
When you run Python scripts from the command line, you can use ArgumentParser to efficiently accept and parse command-line parameters.
one。 Process flow
When using argparse to configure command line parameters, there are three steps:
Create an ArgumentParser () object
Call the add_argument () method to add parameters
Parse the added parameters using parse_args ()
two。 Create an ArgumentParser () object
Create a new ArgumentParser class object, then add several parameter options, and finally parse and get the parameters from the command line through the parse_args () method.
Parser = argparse.ArgumentParser () parser.add_argument ("- p", "--port", dest='port', default= "/ dev/ttyUSB0", help= "serial port where the MCU is connected to.) parser.add_argument ("-v ","-version ", dest='version', action='store_true', help=" show the version number of this program and exit. ") args = parser.parse_args ()
three。 ArgumentParser object add_argument () method
ArgumentParser.add_argument (name or flags... [, action] [, nargs] [, const] [, default] [, type] [, choices] [, required] [, help] [, metavar] [, dest])
Parameters:
Name or flags: the first parameter passed to add_argument () must therefore be a tag sequence or a simple parameter name
Action: indicates how command line arguments should be handled (supported operations: 'store',' store_const','store_true','store_false','append','append_const','count','help','version')
Nargs: associate an action with a different number of command line arguments. (supported values: NMagne.m.n.m.j.m.n.n.m.m.j.m.j.m.r.m.m.r.m.m.r..m..m.r..net.
Const: used to hold constant values that are not read from the command line but are required by the action of ArgumentParser
Default: its default value is None, which indicates what the command line arguments should be if they are not present
Type: allow any necessary type checking and type conversion
Choices: some command line arguments should be selected from a restricted collection
Required: if you want the option to be required, you can specify True as the value of the required= keyword parameter to add_argument ()
Help: a string containing a short description of the parameter
Metavar: by default, the value of dest is used directly for positional parameters, and the value of dest is capitalized for optional parameters. Note that metavar will only change the name displayed. The name of the property in the parse_args () object is still determined by the value of dest.
Dest: for actions with positional parameters, dest is usually provided to add_argument () as the first parameter, and for actions with optional parameters, dest actions are usually derived from the option string, for example, the value of dest generated by ArgumentParser removes the-string before the first long option string. If no long option string is provided, the dest is obtained by removing the-character before the first short option string. Any internal-will be converted to characters to ensure that the string is a valid attribute name. (that is, for optional parameters, find the long option string first, then the short option string, and the internal-is converted to characters. )
four。 Give an example
Example 1
Import argparse parser = argparse.ArgumentParser () parser.add_argument ('- sparse', action='store_true', default=False, help='GAT with sparse version or not.') parser.add_argument ('- seed', type=int, default=72, help='Random seed.') parser.add_argument ('- epochs', type=int, default=10000, help='Number of epochs to train.') Args = parser.parse_args () print (args.sparse) print (args.seed) print (args.epochs)
The result is:
/ home/user/anaconda3/bin/python3.6 / home/user/lly/pyGAT-master/test.pyFalse7210000 Process finished with exit code 0
Example 2
1) General form
But in most cases, the script is likely to require multiple parameters, and the types of parameters are different each time, so it is useful to add tags in front of the parameters to indicate the type and purpose of the parameters, which can be easily achieved with the argparse module.
Also use a script called test.py to take a chestnut:
The import argparseparser = argparse.ArgumentParser (description= "your script description") # description parameter can be used to insert information describing the purpose of the script. You can add a-- verbose tag to the empty parser.add_argument ('--verbose','- vault, action='store_true', help='verbose mode') # and the tag alias can be-v Here action means that when-verbose/-v appears in the read parameter, the verbose of the # parameter dictionary corresponds to True, and the help parameter is used to describe the purpose or meaning of the verbose parameter. Args = parser.parse_args () # saves the variable as a label-value dictionary in the args dictionary if args.verbose:print "Verbose mode on!" else:print "Verbose mode off!"
Running python test.py is followed by-- verbose/-v outputs the former, and if nothing else, the latter. If you enter a parameter other than-- verbose/-v, you will get an error: unrecognized arguments
To mention a little bit, the action parameter indicates how the value is assigned to the key. Here, the bool type is used. If 'count'' means to take the number of times the-- verbose tag appears as the value of verbose, 'append' means that the value after each occurrence of the note will be stored in the same array and then assigned. (well, generally speaking, if you use the latter two less, you won't say much.)
PS:--help tags are created automatically when using the argparse module, so there is generally no need for us to actively define help information.
$python test.py-- helpusage: test.py [- h] [--verbose] your script descriptionoptional arguments:-h,-- help show this help message and exit--verbose,-v verbose mode
2) required parameters
This mode is used to ensure that some required parameters have input.
Parser.add_argument ('--verbose', required=True, type=int)
The required tag means that the-- verbose parameter is required and the type is int, so entering another type will cause an error.
3) position parameters (positional arguments)
Positional parameters are similar to sys.argv calls, with no explicit-- xxx or-xxx tags, so the calling properties are the same as sys.argv.
The first parameter entered by parser.add_argument ('filename') # assigns the key args = parser.parse_args () print "Read in% s" (args.filename) named filename
Input python test.py test.txt will output Read in test.txt
In addition, you can use the nargs parameter to limit the number of positional parameters entered, which defaults to 1. Of course, the nargs parameter can also be used for ordinary tagged parameters.
Parser.add_argument ('num', nargs=2, type=int) means that the script can read in two integers assigned to the num key (in this case, the value is an array of two integers). Nargs can also be used to indicate that if there is a position parameter input, all subsequent inputs will be used as the value of the position parameter;'+ 'means to read at least one position parameter.' ,' Indicates that there is either no or only one position parameter. (PS: consistent with the symbolic use of regular expressions. ) for example, use:
Parser.add_argument ('filename') parser.add_argument (' num', nargs='*)
You can run python test.py text.txt 1 2.
Since there is no label, you need to be careful when using position parameters.
4) input type
It has been mentioned earlier that you can specify the type of input parameter with the type parameter. This type type can also represent the type of file operation to read and write the file directly.
Parser.add_argument ('file', type=argparser.FileType (' r')) # read the file args = parser.parse_args () for line in args.file:print line.strip ()
5) default values of parameters
In general, some default parameters are set so that you do not need to enter some parameters that do not need to be changed every time, but can be achieved by using default parameters.
Parser.add_argument ('filename', default='text.txt')
At this point, you can get Read in text.txt by running python text.py directly without entering a file name.
6) selection of candidate parameters
Indicates that the acceptable value of this parameter can only come from several value candidates, otherwise an error will be reported, just use the choices parameter. For example:
Parser.add_argument ('filename', choices= [' test1.txt', 'text2.txt']) so far, I believe you have a deeper understanding of "how to use argparser". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.