Python3 script programming commonly used.md

[ TOC]

0 x00 Python command line parameters####

There are several ways to achieve command line parameter input:

sys.argv
#! /usr/bin/python
# Function: realize script programming cmd parameter input
import sys

# Method 1 sys module method#
print('The number of parameters is',len(sys.argv),'Parameters')print('List parameter list',str(sys.argv),"\n Calculation results:",end="")
add =0for value in sys.argv:if value == sys.argv[0]:
  pass
 else:
  add +=int(value)print(add)if __name__ =='__main__':
 # Worth learning
 try:
  argv1 = sys.argv[1]
  argv2 = sys.argv[2]
 except Exception as e:print("[*] Error:"+str(e))
  sys.exit()main(sys.argv[1:]) #Pass parameters to the main function

WeiyiGeek.sys.argv

getopt

Python provides the getopt module to get command line parameters (specify the parameter name)
The getopt module is a module that specializes in processing command-line parameters. It is used to obtain command-line options and parameters, that is, sys.argv. Command-line options make program parameters more flexible and support short option mode (-) and long option mode (–) .

grammar:

getopt.getopt(args, options[, long_options])  #Binding of cmd parameters
getopt.gnu_getopt 
getopt.GetoptError  #Exception thrown(This exception is triggered when the parameter list is not found, or the required parameter of the option is empty)- args:List of command line parameters to be parsed.
- options:Defined in string format, colon after options(:)Indicates that the option must have additional parameters. Without a colon, the option has no additional parameters.
- long_options:Defined in the format of a list, long_equal sign after options(=)Indicates that if this option is set, there must be additional parameters, otherwise no additional parameters.
- The return value of this method consists of two elements:the first is(option, value)List of tuples. The second is that the parameter list contains those without'-'or'--'Parameters.

Case: Suppose we create such a script, we can pass two file names to the script file through the command line, and we can view the use of the script through another option.

"""
 File command line parameter description
"""
import sys, getopt
def main(argv):
 inputfile =''
 outputfile =''try:
  opts, args = getopt.getopt(argv,"hi:o:",['help',"ifile=","ofile="])  #Pay attention to attributes(The parameter belongs to the bound property),Return a list of parameters
 except getopt.GetoptError:print('test.py -i <inputfile> -o <outputfile>')
  sys.exit(2)for opt, arg in opts:if opt =='-h' or opt =='--help':print('test.py -i <inputfile> -o <outputfile>')
   sys.exit()
  elif opt in("-i","--ifile"):
   inputfile = arg
  elif opt in("-o","--ofile"):
   outputfile = arg

 print('The input file is:', inputfile)  #Assignment
 print('The output file is:', outputfile)if __name__ =="__main__":main(sys.argv[1:]) #This is also the key point(Exclude the script file itself)

WeiyiGeek.getopt

argparse.ArgumentParser

Description: The argparse module is used as a parser for command line options, parameters and subcommands

Basic syntax:

# Create a parser,The ArgumentParser object will hold all the information needed to convert the command line into a Python data type.
parser = argparse.ArgumentParser(description='Process some integers.',prog='TestArgumentDemo')-prog: program name(default:sys.argv[0])- usage :A string describing the usage of the program(default值:The generated fromarguments are added to the parser)

# Define how to parse a single command line parameter
ArgumentParser.add_argument(name or flags...[, action][, nargs][,const][,default][, type][, choices][, required][, help][, metavar][, dest])
# Parameter analysis:
- name: Specify the parameter name or a list of option strings such as:'-i','--ip'- action :The basic type of action to be taken when this parameter is encountered on the command line
 - ' store'-It only stores the value of the parameter Namespace(foo='1')-'store_const'-It stores the constant value specified by the const parameter name,const=42Namespace(foo=42)-'store_true' and 'store_false'-Yes'store_const'Special cases for storing True and false values respectively,Namespace(foo=True, bar=False, baz=True)-'append'-It stores a list and appends each parameter value to the list. Namespace(foo=['1','2'])-'append_const'-It stores a list, and each parameter value(Constant value)Append to list,Namespace(types=[<class'str'>,<class'int'>])-'count'-Count the number of occurrences of keyword parameters.
 - version—version used in the call=Keyword parameters, and print version information and exit when calling,action='version', version='%(prog)s 2.0 as PROG 2.0 , %(prog)It’s in ArgumentParser, to define prog='PROG
- nargs :The number of command line parameters that should be used(Specify the number of input parameters after the parameter command line)- nargs=2 Specify the number of input parameters followed by the specified parameters
 - nargs=argparse.REMAINDER All remaining command line parameters are collected into a list
- const:Some const and nargs select the required constants.
- default:Default value
- type :The type to which the command line parameter should be converted,str / int / float
 - type=argparse.FileType('r')/ type=argparse.FileType('w')When used with nargs, it allows optional input and output files
- dest :To be added by parse_args()The name of the attribute in the returned object.
- metavar: Using the name of the parameter in the message, when ArgumentParser generates the help message, it needs some way to refer to each expected parameter.
 - By default, ArgumentParser objects use destvalue as the &quot;name&quot; of each object.
 - By default, for positional parameter operations, the dest value is used directly, and for optional parameter operations, the dest value is capitalized.
- choices :Option-a container of allowed values for the parameter.
 - Some command line parameters should be selected from a set of restricted values, choices=['rock','paper','scissors']),choices=range(1,4))- required :Is it possible to omit command line options(Options only/Must or not)。
 - True / False
- help: a short description of the command parameters

actual case:

#! /usr/bin/env python
# coding:utf-8
# Function: understand ArgumentParser and use

import argparse
import os,sys

def main():
 parser = argparse.ArgumentParser(description="""\
  Implement specified input parameters to parse the input value
  Use the ArgumentParser method in the Argparse module to instantiate
  """, prog='TestArgumentDemo')
 parser.add_argument('-i','--ip',dest="ip",type=str,help="""Please enter an IP address such as:192.168.1.1""",required=True)
 parser.add_argument('-u','--user',dest="User",type=str,help="Specify the user name of the connected service",required=True)
 parser.add_argument('-p','--pass',dest="Pass",type=str,help="Specify the user password to connect to the service",required=True)
 parser.add_argument('-P','--port',dest="Port",type=str,help="The port of the specified service default: 25",required=False,default='25')
 parser.add_argument('-v','--version',action="version", version='%(prog)s 1.0')  #argument.py 1.0
 parser.add_argument('-n','--number',dest="Trynum",choices=[1,2,3,4],help="Number of failed retries",default=2,type=int)  #argument.py 1.0
 parser.add_argument('-m','--mutil',dest="Mutil",nargs=2,help="Specify 2 daemon PID values",required=True)  #nargs=argparse.REMAINDER multiple parameters

    
 # Positional parameters: directly read the file package or write
 parser.add_argument('infile',nargs='?',type=argparse.FileType('r'),default=sys.stdin)
 parser.add_argument('outfile',nargs='?',type=argparse.FileType('w+'),default=sys.stdout)

 # You can use metavar to specify an alternative name. When ArgumentParser generates a help message,
 parser.add_argument('--bar',metavar=['XXX','YYYY']) #It needs some way to reference each expected parameter.
 parser.add_argument('demo',metavar=['AAA','bbb'])  #Position parameter prompt

 args = parser.parse_args()print("Parameter Type:",type(args),"\N parameter analysis object:",args)
 ip = args.ip
 username = args.User
 password = args.Pass
 port =int(args.Port) #Since the type specified by the parameter is str, it is converted to int here
 trynum = args.Trynum  #TestArgumentDemo: error: argument -n/--number: invalid choice:5(choose from1,2,3,4)
 mutil = args.Mutil
 print("IP address:",ip)print("username:",username)print("password:",password)print("port:",port)print("number of retries:",trynum)print("Specify the parameter name and multiple parameters:",mutil)print("File reading:",end =" ")for each in args.infile:print(each)print("File writing:",args.outfile)print("Matavar expected parameters: Bar= ",args.bar,"   Demo = ",args.demo)print("Version Information:",end="\t")
 os.system('argument.py -v')if __name__ =='__main__':main()

Results of the:

$argument.py -h
usage: TestArgumentDemo [-h]-i IP -u USER -p PASS [-P PORT][-v][-n {1,2,3,4}]-m MUTIL MUTIL [--bar ['XXX','YYYY']][infile][outfile]['AAA','bbb']

Realize the specified input parameters to parse the input value and use the ArgumentParser method in the Argparse module to instantiate

positional arguments:Location parameter
 infile
 outfile
 [' AAA','bbb']

optional arguments:Option parameter
 - h,--help            show this help message and exit
 - i IP,--ip IP Please enter an IP address such as:192.168.1.1-u USER,--user USER specifies the user name of the connected service
 - p PASS,--pass PASS specifies the user password to connect to the service
 - P PORT,--port PORT Specifies the port of the service. Default: 25-v,--version         show program's version number and exit
 - n {1,2,3,4},--number {1,2,3,4}
      Number of failed retries
 - m MUTIL MUTIL,--mutil MUTIL MUTIL
      Specify 2 daemon PID values
 - - bar ['XXX','YYYY']

$argument.py -i 192.168.1.1-u root -p 123456-P2222 -m 102420481.txt 2.txt AAAA --bar YYYY
Parameter Type:<class'argparse.Namespace'>
Parameter analysis object: Namespace(Mutil=['1024','2048'], Pass='123456', Port='2222', Try
num=2, User='root', bar='YYYY', demo='AAAA', infile=<_io.TextIOWrapper name='1.t
xt' mode='r' encoding='cp936'>, ip='192.168.1.1', outfile=<_io.TextIOWrapper nam
e='2.txt' mode='w+' encoding='cp936'>)
IP address: 192.168.1.1
Username: root
Password: 123456
Port: 2222
Number of retries: 2
Specify the parameter name and multiple parameters:['1024','2048']
File reading: Whoami-Text content
File writing:<_io.TextIOWrapper name='2.txt' mode='w+' encoding='cp936'>
Matavar expected parameters: Bar=  YYYY    Demo =  AAAA
Version information: TestArgumentDemo 1.0

Recommended Posts

Python3 script programming commonly used.md
Python3 interface development commonly used.md
Python network programming
12. Network Programming in Python3
Detailed Python IO programming
Python GUI interface programming
Talking about Python functional programming
Python programming Pycharm fast learning
Python script writing under SecureCRT
Google Python Programming Style Guide
Python commonly used magic methods
Analysis of Python object-oriented programming
XTU programming Python training three
Black Hat Programming Application Python2
Black hat programming application of Python1
How to understand python object-oriented programming
Python classic programming questions: string replacement