search
HomeBackend DevelopmentPython TutorialWhat are the python command line parameters?

What are the python command line parameters?

Jun 25, 2019 am 09:30 AM
pythonCommand line parameters

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
What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.

How do you access elements in a Python list?How do you access elements in a Python list?Apr 26, 2025 am 12:03 AM

ToaccesselementsinaPythonlist,useindexing,negativeindexing,slicing,oriteration.1)Indexingstartsat0.2)Negativeindexingaccessesfromtheend.3)Slicingextractsportions.4)Iterationusesforloopsorenumerate.AlwayschecklistlengthtoavoidIndexError.

How are arrays used in scientific computing with Python?How are arrays used in scientific computing with Python?Apr 25, 2025 am 12:28 AM

ArraysinPython,especiallyviaNumPy,arecrucialinscientificcomputingfortheirefficiencyandversatility.1)Theyareusedfornumericaloperations,dataanalysis,andmachinelearning.2)NumPy'simplementationinCensuresfasteroperationsthanPythonlists.3)Arraysenablequick

How do you handle different Python versions on the same system?How do you handle different Python versions on the same system?Apr 25, 2025 am 12:24 AM

You can manage different Python versions by using pyenv, venv and Anaconda. 1) Use pyenv to manage multiple Python versions: install pyenv, set global and local versions. 2) Use venv to create a virtual environment to isolate project dependencies. 3) Use Anaconda to manage Python versions in your data science project. 4) Keep the system Python for system-level tasks. Through these tools and strategies, you can effectively manage different versions of Python to ensure the smooth running of the project.

What are some advantages of using NumPy arrays over standard Python arrays?What are some advantages of using NumPy arrays over standard Python arrays?Apr 25, 2025 am 12:21 AM

NumPyarrayshaveseveraladvantagesoverstandardPythonarrays:1)TheyaremuchfasterduetoC-basedimplementation,2)Theyaremorememory-efficient,especiallywithlargedatasets,and3)Theyofferoptimized,vectorizedfunctionsformathematicalandstatisticaloperations,making

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!