程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python argparse

編輯:Python

argparse  Module makes it easy to write user-friendly command-line interface . The program defines the parameters it needs , then  argparse  Will find out how to start from  sys.argv  Parse out those parameters . argparse  The module also automatically generates help and user manuals , And report an error message when the user passes in invalid parameters to the program .
Use argparse Three steps to pass in parameters from the command line :
1, The first step is to create a ArgumentParser object :
        parser = argparse.ArgumentParser(description='process some integers')
2, The second step calls add_argument() Method to add parameters
        parser.add_argument('-f',       'binfile',        default='',      help='input bin file')
3, The third step calls parse_args() Method to parse parameters , Then we can use args.binfile Call the parameter
        args = parser.parse_args()

One ,ArgumentParser() Parameters that can be added in parentheses

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, allow_abbrev=True)
Create a new ArgumentParser object . All parameters should be passed in as keyword parameters . Each parameter is described in more detail below , But in short , They are :
prog - Program name ( The default value is :sys.argv[0])
usage - A string describing the purpose of the program ( The default value is : Generate... From parameters added to the parser )
description - The text displayed before the parameter help document ( The default value is : nothing )
epilog - The text displayed after the parameter help document ( The default value is : nothing )
parents - One ArgumentParser List of objects , Their parameters should also be included
formatter_class - A class for customizing the output format of help documents
prefix_chars - Prefix character set of optional parameters ( The default value is : ‘-‘)
fromfile_prefix_chars - When other parameters need to be read from the file , Prefix character set used to identify file names ( The default value is : None)
argument_default - Global default values for parameters ( The default value is : None)
conflict_handler - Policies for resolving conflict options ( Usually not necessary )
add_help - Add a... To the parser -h/--help Options ( The default value is : True)
allow_abbrev - If the abbreviation is unambiguous , The abbreviated long option is allowed ( The default value is :True)
stay 3.5 Version change : Added allow_abbrev Parameters .
  • description Parameters and epilog Parameters , See figure below ,description It's on the front ,epilog Show at the end


  •  prefix_chars Parameters , Generally, the command line will default to - As a prefix , such as -f,-l etc. . If you want other characters as prefixes, you can use this parameter to define . Pay attention not only to -f Modified into +f, Try to make --binfile Change to ++binfile.

  Two ,add_argument

The regular usage is as follows :

import argparse
demo_doc="change bin file to hex"
parser = argparse.ArgumentParser(formatter_class.RawTextHelpFormatter,epilog=demo_doc)
parser.add_argument('-f' ,'--binfile' ,default='' ,help='input bin file')
parser.add_argument('-d' ,'--start_addr' ,default='' ,help='input bin file')
args = parser.parse_args

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]), A brief description of parameter usage is as follows :

name or flags - A list of named or option strings , for example foo or -f, --foo.
action - The basic type of action used when parameters appear on the command line .
nargs - The number of command line arguments that should be consumed .
const - By some action and nargs Select the required constant .
default - The value used when the parameter does not appear on the command line .
type - The type to which command line arguments should be converted .
choices - Container of available parameters .
required - Whether this command line option can be omitted ( Only options are available ).
help - A brief description of the effect of this option .
metavar - Example of parameter values used in usage method messages .
dest - Be added to parse_args() The property name on the returned object .

add_argument Option parameters are passed - Prefix identification , No addition - It will be recognized as a position parameter :
Creation of option parameters :parser.add_argument('-f', '--foo')
Creation of position parameters :parser.add_argument('bar')

  • action Parameters :

‘store’ Store the value of the parameter , This is a action The default value of .
‘store_const’ Storage is const The value specified by the named parameter .

 ‘store_true' and 'store_false', yes ’store_const‘ Separately used for storage True and False Worth special use cases , The default values are True and False.

’append' Store a list , And append each parameter value to the list . 

 ‘version’ Add a version information parameter

For more parameter information, please see  16.4. argparse — Command line options 、 Parameter and subcommand parsers — Python 3.5.10 file

  • nargs Parameters , Store multiple parameters as a list

N An integer , On the command line N Parameters will be saved in a list ,N by 1 when , What is stored is a list with only one data

 '?' If there are parameters, a number is stored ( It's not a list ), Save without parameters default value , If you enter a flag entry on the command line , But if it is not followed by a parameter, it will be saved const The number that follows

‘*’ All input parameters in the command line are saved in a list .

 ‘+’, and ‘*’ similar , All current command line parameters are aggregated into a list , If there is no parameter, an error will be reported .
argparse.REMAINDER, All remaining command line parameters are aggregated into a list .

  •  const This parameter is used to save the constant value that is not read from the command line but will be required ( It can be for string String of type ). The two most common examples are as follows :

  •  default  Specifies the default value that should be used when the command line parameter does not appear , The default value is None, Use type Parameters can be used for default Data type conversion .
  •  type By default ,ArgumentParser Object reads command line arguments as simple strings , have access to type Convert the input parameter type , such as float,int. You can also do it in type Call the function after the parameter to convert the parameter , And return the converted value .

  •  choice Check whether the input parameters are within a range ., If the parameter value is not one of the acceptable values, an error message is displayed  

  •  require Usually, the parameters to be entered are optional , It can be ignored on the command line ( That is, you can not enter this parameter ), To make an option necessary , Then you can put True As required= Key words to add_argument()
  • help Is a string describing the parameter , When used on the command line -h perhaps --help When , these help The description is displayed with each parameter .
  • metavar When the help message appears on the screen , The name displayed after the parameter can be overwritten with this parameter
  • dest have access to dest Parameter to define the name of the input parameter , For optional parameters ,dest The value of is usually taken from the option string .ArgumentParser It will pass the first long option string and remove the beginning -- String to generate dest Value . If no long option string is provided , be dest By accepting the first short option string and removing the leading - Character to get . Any internal - Characters will be converted to _ Character to ensure that the string is a valid attribute name .

This article is a summary of my own use , The following articles are cited at large in the parameter interpretation section , Please move to the following link to support the original version . 16.4. argparse — Command line options 、 Parameter and subcommand parsers — Python 3.5.10 file https://docs.python.org/zh-cn/3.5/library/argparse.html#argparse.Action


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved