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

Most complete summary: talk about several ways of Python command line parameterization

編輯:Python

Hello everyone , In daily writing Python In the process of scripting , We often need to pass in some variable parameters in combination with command line parameters , Make the project more flexible and convenient

In this article, I will list the build Python Of command line arguments 4 There are two common ways

They are :

  • built-in sys.argv modular

  • built-in argparse modular

  • built-in getopt modular

  • Third party dependency Library click

1. sys.argv

Easiest to build command line parameters 、 A common way is to use the built-in 「 sys.argv 」 modular

It passes parameters in an ordered list , Therefore, the order of parameter transfer must be fixed

therefore , This method is applicable to projects with few parameters and fixed scenarios

import sys
if __name__ == '__main__':
# Get parameter list 
# Be careful :sys.argv[0] Represents the first parameter , namely : Script name 「1_sys.argv.py」
# List of other parameters 
args = sys.argv[1:]
# Number of parameters 
args_length = len(sys.argv) if sys.argv else 0
print(" Exclude run master file parameters , Other parameter lists are :", args)
print(" Total number of parameters :", args_length)
# Use 
# python3 1_sys.argv.py arg1 arg2
# Exclude run master file parameters , Other parameter lists are : [arg1, arg1]
# Total number of parameters :3

It should be noted that , Pass... In the script 「 sys.argv 」 Get the parameter list , The first parameter represents the name of the script main file

2. argparse

Built in argparse The module can easily write friendly command line parameter scripts , And it can automatically generate help manuals , Clear error messages can be thrown when the user passes invalid parameters into the program

Official documents :

https://docs.python.org/zh-cn/3.10/library/argparse.html

Use it to build command line arguments that contain 3 A step :

 Build parameter resolution object add parameter add parameter resolution parameter
3-1 Build command line parameter parsing object
import argparse
...
# Build a command line parameter parsing object 
parser = argparse.ArgumentParser(description=' Command line arguments ')
...
3-2 Add command line arguments
 It's important to point out that ,--arg1 Used to specify the parameter name ,-a1 representative dest Target variable value ( Abbreviation )
...
# Set up 3 Parameters 
# Parameters 1:arg1, integer , It is not necessary to pass in parameters 
# Parameters 2:arg2, character string , It is not necessary to pass in parameters , Include default values 「xag」
# Parameters 3:arg3, String type , Parameters that must be passed in 
parser.add_argument('--arg1', '-a1', type=int, help=' Parameters 1, Not a required parameter ')
parser.add_argument('--arg2', '-a2', type=str, help=' Parameters 2, Not a required parameter , Include default values ', default='xag')
parser.add_argument('--arg3', '-a3', type=str, help=' Parameters 3, Necessary parameters ', required=True)
...
3-3 Analyze the parameter value
...
# Analytical parameters , Get all command line parameters (Namespace), Then turn it into a dictionary 
args = vars(parser.parse_args())
# Get all parameters 
print(" All command line parameters are :")
for key in args:
print(f" Command line parameter name :{
key}, Parameter values :{
args[key]}")
...
 When you use it , We can go through 「 -h / --help 」 Command parameters view help documentation
# View the command line parameter help documentation 
python3 2_argparse.py --help
# or 
python3 2_argparse.py -h

Added above 3 Parameters , Parameters arg1、arg2 Non mandatory value transfer ,arg3 Must pass value , Another parameter arg2 Default value specified

# Parameters arg3 must , Parameters arg1 And parameters arg2 Not necessary , The parameter arg2 Set the default value 
# Pass in the parameter arg3
# python3 2_argparse.py --arg3 123
# python3 2_argparse.py -a3 123 
[email protected]-Pro args % python3 2_argparse.py -a3 123
All command line parameters are :
Command line parameter name :arg1, Parameter values :None
Command line parameter name :arg2, Parameter values :xag
Command line parameter name :arg3, Parameter values :123
# Pass in the parameter arg1、arg3
[email protected]-Pro args % python3 2_argparse.py -a1 111 -a3 123
All command line parameters are :
Command line parameter name :arg1, Parameter values :111
Command line parameter name :arg2, Parameter values :xag
Command line parameter name :arg3, Parameter values :123
# Pass in the parameter arg1、arg2、arg3
[email protected]-Pro args % python3 2_argparse.py -a1 111 -a2 222 -a3 123
All command line parameters are :
Command line parameter name :arg1, Parameter values :111
Command line parameter name :arg2, Parameter values :222
Command line parameter name :arg3, Parameter values :123

3. getopt

getopt yes Python A built-in standard module in , Can combine sys.argv modular , Directly parse script runtime parameters

Use format :getopt(args,shortopts,longopts = [])

among

  • args

    parameter list , Can pass sys.argv obtain , You can refer to the above

  • shortopts A string consisting of short parameters

    Define short parameters , If the parameter has a value , You need to append a... After the short parameter 「 : 」 Symbol

    How to use parameters :-n 23

  • longopts Long parameter list

    When defining a long parameter list , If a parameter has a value , You need to append a... After the short parameter 「 = 」 Symbol

    How to use parameters :–port 8080

Take the incoming database connection parameters as an example ( Parameters include ip、 user name 、 password 、 Database name ) Explain

from getopt import getopt
import sys
# To obtain parameters 
# sys.argv[1:]: Get all the command line parameters except the script file name 
# opts: A tuple list of all options and their input values 
# args: Remove the rest of the useful input 
opts, args = getopt(sys.argv[1:], 'i:u:p:d:', ['ip=', 'user=', 'pwd=', 'db='])
# Get parameter value 
# Short parameters 
# python3 4_getopt.py -i 127.0.0.1 -u root -p 123456 -d mysqldb
# Long parameters 
# python3 4_getopt.py --ip 127.0.0.1 -u root -p 123456 -d mysqldb
ip_pre = [item[1] for item in opts if item[0] in ('-i', '--ip')]
ip = ip_pre[0] if len(ip_pre) > 0 else None
print(" Parameters ip:", ip)
user_pre = [item[1] for item in opts if item[0] in ('-u', '--user')]
user = user_pre[0] if len(user_pre) > 0 else None
print(" Parameters user:", user)
pwd_pre = [item[1] for item in opts if item[0] in ('-p', '--pwd')]
pwd = pwd_pre[0] if len(pwd_pre) > 0 else None
print(" Parameters pwd:", pwd)
db_pre = [item[1] for item in opts if item[0] in ('-d', '--db')]
db = db_pre[0] if len(db_pre) > 0 else None
print(" Parameters db:", db)

When running the script , We can use 「 Short parameters 」 or 「 Long parameters 」 Transfer in form

# test 
# Short parameters 
python3 4_getopt.py -i 127.0.0.1 -u root -p 123456 -d mysqldb
# Long parameters 
python3 4_getopt.py --ip 127.0.0.1 --user root --pwd 123456 --db mysqldb

4. click

click As a third-party dependent Library , It encapsulates a number of methods for command-line tools , It is very convenient to implement command line parameters

Project address :https://pypi.org/project/click/

First , We need to install dependency Libraries click

import click
# Installation dependency 
# pip3 install -U click
@click.command()
@click.option('--arg1', default='111', help=' Parameters arg1, The default value is 「111」')
@click.option('--arg2', type=int, help=' Parameters arg2')
@click.option('--arg3', type=str, help=' Parameters arg3')
def start(arg1, arg2, arg3):
""" Based on parameters arg1、 Parameters arg2、 Parameters arg3 Run the project :param arg1: :param arg2: :param arg3: :return: """
print(" Parameters arg1 The value is :", arg1)
print(" Parameters arg2 The value is :", arg2)
print(" Parameters arg3 The value is :", arg3)
if __name__ == '__main__':
start()

then , You can configure parameters on the main running function through the decorator

such as , The above defines 3 Two command line arguments arg1、arg2、arg3, And set the parameter type and default value

Last , When running the script, you only need to pass the corresponding value according to the parameter settings

# No parameters 
[email protected]-Pro args % python3 3_click.py
Parameters arg1 The value is : 111
Parameters arg2 The value is : None
Parameters arg3 The value is : None
# Include parameters arg1
[email protected]-Pro args % python3 3_click.py --arg1 test1
Parameters arg1 The value is : test1
Parameters arg2 The value is : None
Parameters arg3 The value is : None
# Include parameters arg1、arg2
# Be careful :arg2 The parameter type of is integer , The passed in parameter must be able to be converted to an integer , Otherwise, an error will be reported 
[email protected]-Pro args % python3 3_click.py --arg1 test1 --arg2 222
Parameters arg1 The value is : test1
Parameters arg2 The value is : 222
Parameters arg3 The value is : None
# Include parameters arg1、arg2、arg3
[email protected]-Pro args % python3 3_click.py --arg1 test1 --arg2 222 --arg3 test3
Parameters arg1 The value is : test1
Parameters arg2 The value is : 222
Parameters arg3 The value is : test3

Last

The above explains the implementation through an example Python Command line arguments are common 4 Ways of planting

For some simple and informal scenarios , Personally, I think we can consider using sys.argv Modules quickly build command line parameters ; For some parameters, there are many 、 Formal production environment for users , It is suggested to make use of argparse Module or click Dependency to create command line parameters

Technical communication

Welcome to reprint 、 Collection 、 Gain some praise and support ! data 、 The code can be obtained from me

At present, a technical exchange group has been opened , Group friends have exceeded 2000 people , The best way to add notes is : source + Interest direction , Easy to find like-minded friends

  • The way ①、 Send the following picture to wechat , Long press recognition , The background to reply : Add group ;
  • The way ②、 Add microsignals :dkl88191, remarks : come from CSDN
  • The way ③、 WeChat search official account :Python Learning and data mining , The background to reply : Add group


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