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_compileargparse
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!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
