Home  >  Article  >  Backend Development  >  What are the python command line parameters?

What are the python command line parameters?

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-25 09:30:196003browse

What are the python command line parameters?

What are the python command line parameters? Let me give you a detailed introduction to what command line parameters are:

sys.argv

You can also use sys's sys.argv in Python. Get command line parameters:

sys.argv is the command line parameter list.

len(sys.argv) is the number of command line parameters.

sys.argv[0] is the name of the script file, such as: test.py

sys.argv[1:] is a space-separated parameter list

getopt

Function prototype:

getopt(args, shortopts, longopts = [])

Parameters:
args: parameters that need to be parsed, usually sys.argv[1:]
shortopts: short format (-), with a colon: indicates that the parameter value is required after the parameter, without a colon, indicating that no parameter value is required after the parameter
longopts: long format (--), with an equal sign, indicating that a parameter value is required after the parameter, without an equal sign, indicating that no parameter is required after the parameter Value
Return value:
options is a list containing ancestors. Each ancestor is the format information analyzed, such as [('-i','127.0.0.1'),('-p','80 ')] ;
args is a list, including those parameters without '-' or '--', such as: ['55','66']

Related recommendations: "Python Video tutorial

Example:

import sys
import getopt
try:    
    options,args = getopt.getopt(sys.argv[1:],"hp:i:", ["help","ip=","port="])
except getopt.GetoptError:    
    sys.exit()
for name,value in options:   
    if name in ("-h","--help"):        
        usage()    
    if name in ("-i","--ip"):        
        print 'ip is----',value    
    if name in ("-p","--port"):        
    print 'port is----',value
python test.py -i 127.0.0.1 -p 80 55 66
python test.py --ip=127.0.0.1 --port=80 55 66

"hp:i:"
Short format --- No colon after h: means no parameters, p: and i : There is a colon after it, indicating that parameters are needed later
["help","ip=","port="]
Long format --- There is no equal sign = after help, which means there are no parameters behind it, and the other three There is =, indicating that parameters are required later
Note: When defining command line parameters, you must first define parameters with the '-' option, and then define parameters without '-'

optparse

Class OptionParser

class optparse.OptionParser(usage=None, 
                 option_list=None,
                 option_class=Option,
                 version=None,
                 conflict_handler="error",
                 description=None,
                 formatter=None,
                 add_help_option=True,
                 prog=None,
                 epilog=None)

Parameters:

usage: Usage instructions for the program, where "%prog" will be replaced with the file name (or prog attribute, if the prog attribute is specified value), "[options]" will be replaced with the instructions for each parameter
version: version number

Function add_option()

add_option(short, long, action, type, dest, default, help)

Parameters:
short option string: is the first parameter, indicating the abbreviation of option, such as -f;
long option string: is the second parameter, indicating the full spelling of option, such as --file;
action=: Indicates the processing method for this option. The default value is store, which means storing the value of option into the members of the parsed options object.

Action can also have other values: for bool values, use store_true to store true by default, use store_false to store false by default, store_const is used to store the value set by const to this option, and append means adding parameters to the option. into the list. At this time, the option is a list, which may contain multiple values. Count means increasing the counter by one, and callback means calling the specified function. All action values ​​are as follows:
store store_true store_false store_const append count callback

type=: Indicates the type of the value of this option, the default is string, and can be specified as string, int, choice, float and complex;
dest=: Indicates the name of the member of this option in the options object parsed by optionparser. By default, long option string is used;
help=: Indicates the usage instructions of this parameter;
default=: Indicates than option The default value of , you need to set this value;


Function parse_args

(options, args) = parser.parse_args()
Return value: options is a directory, its content is the key of "parameter/value" value pair.

args is a list, its content is the remaining input content after removing options from all parameters.


Simple usage:

from optparse import OptionParser  
  
parser = OptionParser(usage="usage:%prog [options] arg1 arg2")  
parser.add_option("-t", "--timeout",  
                action = "store",  
                type = 'int',  
                dest = "timeout",  
                default = None,  
                help="Specify annalysis execution time limit"  
                )  
parser.add_option("-u", "--url",  
                action = "store_true",  
                dest = "url",  
                default = False,  
                help = "Specify if the target is an URL"  
                )
(options, args) = parser.parse_args() 
if options.url:  
    print(args[0])

Complex usage: parameter grouping

parser = optparse.OptionParser(version="%prog " + config.version)# common_groupcommon_group = optparse.OptionGroup(
    parser, "Common Options",    "Common options for code-coverage.")
parser.add_option_group(common_group)
common_group.add_option(    "-l", "--lang", dest="lang", type="string", default="cpp",    help="module language.", metavar="STRING")
common_group.add_option(    "--module_id", dest="module_id", type="int", default=None,    help="module id.", metavar="INT")
cpp_group = optparse.OptionGroup(
    parser, "C/C++ Options",    "Special options for C/C++.")# cpp_groupparser.add_option_group(cpp_group)
cpp_group.add_option(    "--local-compile", action="store_true", dest="local_compile",    help="compile locally, do not use compile cluster.")
cpp_group.add_option(    "--module_path", dest="module_path", type="string", default=None,    help="module path, like app/ecom/nova/se/se-as.", metavar="STRING")
    
options, arguments = parser.parse_args()
lang = options.lang
module_id = options.module_id
local_compile = options.local_compile
module_path = options.local_compile
argparse

Class ArgumentParser

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)

Parameters:

prog: the name of the program (default: sys.argv[0])

usage: a string describing the usage of the program (default: generated from the parameters of the parser)

description: The text before the parameter help information (default: empty)
epilog: The text after the parameter help information (default: empty)
parents: A list of ArgumentParser objects, the parameters of these objects should be included
formatter_class: A class for customized help information
prefix_chars: The prefix character set of optional parameters (default: '-')
fromfile_prefix_chars: The prefix character set of the file that additional parameters should be read from (default: None)
argument_default: Global default value for the argument (default: None)
conflict_handler: Strategy for resolving conflicting optional arguments (usually not necessary)
add_help: Add the -h/–help option to the parser (default: True)


Function add_argument()

add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help]
[, metavar][, dest])

参数:
name or flags:选项字符串的名字或者列表,例如foo 或者-f, --foo。
action:在命令行遇到该参数时采取的基本动作类型。
nargs:应该读取的命令行参数数目。
const:某些action和nargs选项要求的常数值。
default:如果命令行中没有出现该参数时的默认值。
type:命令行参数应该被转换成的类型。
choices:参数可允许的值的一个容器。
required:该命令行选项是否可以省略(只针对可选参数)。
help:参数的简短描述。
metavar:参数在帮助信息中的名字。
dest:给parse_args()返回的对象要添加的属性名称。

简单用法:

import argparse
parser = argparse.ArgumentParser(description="progrom description")
parser.add_argument('key', help="Redis key where items are stored")
parser.add_argument('--host')
arser.add_argument('--port')
parser.add_argument('--timeout', type=int, default=5)
parser.add_argument('--limit', type=int, default=0)
parser.add_argument('--progress_every', type=int, default=100)
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
key = args.key
host = args.host
port = args.port
timeout = args.timeout
limit = args.limit
progress-every = args.progress_every
verbose = args.verbose

The above is the detailed content of What are the python command line parameters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn