Home Backend Development Python Tutorial What are the python command line parameters?

What are the python command line parameters?

Jun 25, 2019 am 09:30 AM
python Command 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 = [])
Copy after login

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
Copy after login

"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)
Copy after login

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)
Copy after login

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()
Copy after login
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])
Copy after login

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
Copy after login
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)
Copy after login

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])
Copy after login

参数:
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
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

See all articles