python command line parameters

Most of us use python to write scripts in our daily work or study. How can our script program perform any operation through the command line like the cmd window of Windows and the shell window of Linux?

Three built-in modules in python are used to process command line parameters:

  sys

  getopt

  optparse

  argparse

 

1, sys command line parameters

The sys module is mainly used to obtain information related to the Python interpreter. You can first import the sys module import sys in the python interactive interpreter. Query all the names defined in the module through the built-in function dir() and return them in the form of a string list.

                                 

 

 

sys.argv: get the command line parameters of the running Python program in a list. Where, sys Argv [0] usually refers to the python program itself, sys Argv [1] represents the first parameter, sys Argv [2] represents the second parameter, and so on.

 

import sys

def start(argv):
    print('Program name:',argv[0])
    print('First parameter:',argv[1])
    print('Second parameter:',argv[2])
    print('Third parameter:',argv[3])

if __name__ == '__main__':
    try:
        start(sys.argv[0:])
    except KeyboardInterrupt:
        print("interrupted by user, killing all threads...")

 

2, getopt command line parameter

Getopt is for sys Argv gets the command line parameters for secondary processing. When running the program, you may need to enter different command-line options according to different conditions to achieve different functions. For example, - u represents the user and - p represents the password. Call getopt Getopt () returns two lists. The first list is assigned to opts and the second list is assigned to args.

opts: Yes (option, option value) tuple is a list of elements. If there is no option, the value is an empty string;

args: a list of unused menu parameters. Remaining command line parameters that do not belong to format information;

 

import sys,getopt

opts, args = getopt.getopt(sys.argv[1:], "u:p:", ["file="])
print("opts The result is:",opts)
print("args The result is:",args)

Parameter interpretation: use sys Argv [1:] is the first parameter for filtering (the first parameter is the Python program itself) "u:p:" defines the short format option (-). Here, u and p are two options. "u:p:" followed by ":" must have an option value.

["file ="] defines the long format option (- -). The "=" here is the same as the ":" in the short format option above, and must be followed by the option value.

 

Use the command: Python 3/ getoptdemo. py -u user -p password --file=123. txt 123456

 

 

 

3, optparse command line parameter

 

The optparse module is mainly used to pass command parameters to scripts, and uses predefined options to parse command line parameters. Unlike the getopt function, optparse can automatically generate help information.

 

import optparse

usage = "python %prog -u/--user <target user> -p/--password <target password>"
parser = optparse.OptionParser(usage)
parser.add_option('-u', '--user',dest='User',type='string',help='target user', default='root')
parser.add_option('-p', '--password',dest='Pwd',type='string',help='target password')
options, args = parser.parse_args()

print("options Is:",options) print("User name is", options.User) print("Password is", options.Pwd)
print("args Is:",args)

 

Use the command: Python 3 \optparsedemo. py -h

     python3 .\optparsedemo.py -u user -p password

 

 

4, argparse command line parameter

 

Argparse is an upgraded version of optparse module. Compared with optparse, argparse module is simpler and more convenient to use.

 

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user', dest='User', type=str,default='root', help = 'target User')
parser.add_argument('-s', '--sex', dest='Sex', type=str,choices=['male','female'],default='male', help = 'target Sex')
parser.add_argument('-n', '--number', dest='Num',nargs=2,required=True, type=int, help = 'target Two Numbers')

print(parser.parse_args())

 

 

Use the command: Python 3 \argparsedemo. py -h

     python3 .\argparsedemo.py -n 12 15 

 

 

argparse.ArgumentParser().add_argument parameter:

Multiple option strings can be set, such as' - u 'and' - user 'above. Choose one of them when using;

Type is used to check whether the data type of the input parameters on the command line meets the requirements, including string, int, float and other types;

dest = used to define the location where the option values are stored, as the key of the first dictionary (options), and the value is the parameter entered by the command;

Help is used to define help information;

Default sets the default value;

 

Keywords: Python

Added by enemeth on Mon, 03 Jan 2022 03:59:42 +0200