Getopt module in Python
The getopt module is a parser for command-line options based on the convention established by the Unix
getopt() function. It is in general used for parsing an argument sequence such as sys.argv. In other words, this module helps scripts to parse command-line arguments in sys.argv. It works similar to the C
getopt() function for parsing command-line parameters.
Python getopt function
The first function provided by this module is of the same name i.e.
getopt(). Its primary functionality is to parse command-line options and parameter list. The syntax of the function is as below:
Syntax: getopt.getopt(args, options, [long_options])
args: List of arguments to be passed.
options: String of option letters that the script wants to recognize. Options that require an argument should be followed by a colon (:).
long_options: List of the string with the name of long options. Options that require arguments should be followed by an equal sign (=).
Return Type: Returns value consisting 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.
Here we have created a function
full_name(), which prints the full name after getting first name and last name from the command line. We have also abbreviated first name as ‘f’ and last name as ‘l’.
Example 2: Now lets look into the case where instead of short-form like ‘f’ or ‘l’, we could use full forms as ‘first_name’ and ‘last_name’.The below code uses full forms to print full name;
Note: The single dash(‘-‘) for short forms and double dash(‘–‘) for long form of the argument in the code should be used.
Please Login to comment...