Detailed explanation of how python obtains the executed command parameters through getopt module

Keywords: Python shell Unix Web Development

This article mainly introduces to you the relevant information about how python obtains the executed command parameters through getopt module. The example code is introduced in detail in this article, which has a certain reference learning value for your study or work. The friends who need it will learn together with the editor.
Preface

python script and shell script can get the parameters of the command line, and perform different logical processing according to different parameters.

Usually we can get different execution commands and parameters through getopt module. Let's have a look at the detailed introduction.
The method is as follows:

Next, I will explain the use of this module by creating a new test.py script

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import getopt
if __name__=='__main__':
 print sys.argv
 opts, args = getopt.getopt(sys.argv[1:], "ht:q:", ["url=",'out'])
 print opts
 print args

Execute command:. / test3.py -t 20171010-20171011 -q 24 -h --url=https://www.baidu.com --out file1 file2
Execution result:

['D:/GitReposity/hope_crontab_repo/sla_channel/test3.py', '-t', '20171010-20171011', '-q', '24', '-h', '--url=https://www.baidu.com', '--out', 'file1', 'file2']
[('-t', '20171010-20171011'), ('-q', '24'), ('-h', ''), ('--url', 'https://www.baidu.com'), ('--out', '')]
['file1', 'file2']

Let's check the official document of getopt module

def getopt(args, shortopts, longopts = [])
 
Parses command line options and parameter list. args is the
argument list to be parsed, without the leading reference to the
running program. Typically, this means "sys.argv[1:]". shortopts
is the string of option letters that the script wants to
recognize, with options that require an argument followed by a
colon (i.e., the same format that Unix getopt() uses). If
specified, longopts is a list of strings with the names of the
long options which should be supported. The leading '--'
characters should not be included in the option name. Options
which require an argument should be followed by an equal sign
('=').
 
The return value consists of two elements: the first is a list of
(option, value) pairs; the second is the list of program arguments
left after the option list was stripped (this is a trailing slice
of the first argument). Each option-and-value pair returned has
the option as its first element, prefixed with a hyphen (e.g.,
'-x'), and the option argument as its second element, or an empty
string if the option has no argument. The options occur in the
list in the same order in which they were found, thus allowing
multiple occurrences. Long and short options may be mixed.

You can see that the getopt method requires three parameters.

The first parameter is args, which is the command-line parameter to be resolved. We can get the execution related parameters through sys.argv

['D:/GitReposity/hope_crontab_repo/sla_channel/test3.py', '-t', '20171010-20171011', '-q', '24', '-h', '--url=https://www.baidu.com']

You can see that the first value of the parameter list is the full path name of the script execution, and the remaining parameters are command-line parameters separated by spaces. In order to obtain valid parameters, usually the value of args parameter is sys.argv[1:].

The second parameter is shortops, which is a short command operator. Its parameters should contain parameters starting with - Symbols in the command line. Like qht in the above example, which starts with - so qht is the short command of the script. How does the short command match the parameters? As you can see in the example, shotops is "h t: q:". Here, the command is followed by: to declare whether the command requires parameters. Here, H does not need parameters, t and q need parameters. The parameters immediately following T and q in the command line are their command parameters, that is, t's command parameters are 20171010-20171011, and q's command parameters are 24.

The third parameter is LONGOPS, which is an array to represent the set of long command operators. This set should contain the parameters starting with the - symbol in the command line. Both URL and out are long commands. When the long command ends with = it means that it needs a parameter, such as "url =", which matches the next parameter in the command line https://www.baidu.com

This method returns two array elements. The first return value is the primitive ancestor of the command line and its parameters that are matched by shortops and LONGOPS. The return value of this example is:

[('-t', '20171010-20171011'), ('-q', '24'), ('-h', ''), ('--url', 'https://www.baidu.com'), ('--out', '')]
['file1', 'file2']

The second return value is an unmatched parameter in the command line. The return value of this example is:

['file1', 'file2']

Through the return value, we can design different logic processing according to different commands in our own code, which enriches the usability of scripts.

Recommend our Python learning button qun: 913066266, and see how the seniors learn! From the basic Python script to web development, crawler, django, data mining and so on [PDF, actual source], the data from zero base to project actual combat have been sorted out. To everyone in Python! Every day, Daniel regularly explains Python technology, shares some learning methods and small details that need attention, and click to join our python learners' gathering place

47 original articles published, 51 praised, 50000 visitors+
Private letter follow

Posted by PHPrev on Tue, 11 Feb 2020 06:37:12 -0800