Learn Python – Getopt module in Python- Basic and advance

The getopt modules is analyser used for command-line options, which are primarily based on the convention geared up by means of the UNIX getopt() function. It is basically used to analysing an argument sequence like sys.argv. We can also apprehend this module as it helps the scripts to analyse the command – line arguments in sys.argv. This module works like the C programming language getotp() function for analysing the command – line parameters.

Python getopt Function

This modules provide some essential function that is the (goes with the aid of the identical identify that is) getopt(). The performance of this characteristic is to analyse command – line preferences and parameter lists.

Syntax:

getopt.getopt ( args , options , [ long_options ] )  

Parameters:

The getopt.getopt() module takes the following parameters.

args: The args is the listing of arguments which are to be surpassed

options: The picks are the string of picks letters which the script wants to recognize. The choice that needs arguments need to be written with a colon ( :).

long_options: This is the listing of the string which have the title of lengthy options. The alternative that wants arguments must be written with an equal signal ( = ).

Return Type: The return price of getopt () module function consists of two elements. The first component of the return value is the listing of ( alternative , fee ) pairs, and the 2nd aspect of the return fee is a listing of application arguments which are left when the choices list used to be stripped.

Supported option syntax includes:

-   - a  
-   - bvalue  
-   - b value  
-   -- noargument  
-   -- withargument=value  
-   -- withargument value  

Function Arguments of Getopt()

The getopt ( ) module characteristic takes three arguments:

The first argument of the getopt() module consists of the classification of the arguments to be analysed. This generally derives from sys.argv [ 1: ] (the program name is ignored in sys.argv [ 0 ] ) argument sequence.

The second argument is the string which is the option definition for single-character options. If any of the option needs an argument, its letter is written with a colon [ : ].

The third argument of the getopt ( ) module function is the sequence of the names of the long-style option. Long – style options name can be consisting of more than a single character, for example: — noargument or — witharguement. The name of options in the sequence of arguments must not include the ” — ” prefix. If any long – style option needs an argument, and its name should be written with equals ( = ) to sign.

Users can mix the Long and brief structure of the options in a single call.

Short Form Options:

Suppose the user’s program is taking two preferences ‘ – a ‘ and ‘ – b ‘ with the ‘ – b ‘ alternative wants an argument, then the price need to be ” ab: “.

import getopt     #importing the getopt module  
  
print getopt.getopt ( [ ' -a ' , ' -bval ' , ' -c ' , ' val ' ] , ' ab:c: ' )  
$ python getopt_short.py  
  
( [ ( ' -a ' , ' ' ) , ( ' -b ' , ' val ' ) , ( ' -c ' , ' val ' ) ] , [ ] )  

Long-form options in Getopt ( )

If the user’s software wants to take two options, such as, ” – noarguement ” and ” – witharguement ” then, the sequence of the arguements will be [ ‘ noarguement ‘ , ‘ witharguement= ‘ ].

import getopt                               # importing getopt () module  
print getopt.getopt ( [ ' -noarguement ' , ' -witharguement ' , ' value ' , ' -witharguement2 = another ' ] , '  ' , [ ' noarguement ' , ' witharguement = ' , ' witharguement2 = ' ] )  
$ python getopt_long.py  
( [ ( ' -noarguement ' , ' ' ) , ( '?witharguement ' , ' value ' ) , ( ' -witharguement2 ' , ' another ' ) ] , [ ] )  

Example 1:

import sys                                                   
# importing getopt module                           
import getopt    
  
def full_name ( ):   
    first_name = None  
    last_name = None  
    
    argv = sys.argv [ 1: ]   
    
    try:   
        opts , args = getopt.getopt ( argv, " f:l: " )   
        
    except:   
        print ( " Error " )   
    
    for opt , arg in opts:   
        if opt in [ ' -f ' ]:   
            first_name = arg   
        elif opt in [ ' -l ' ] :   
            last_name = arg   
        
    
    print ( first_name + " " + last_name )   
    
full_name ( )   

Output:

Here, the person has created a feature full_name(), which will print the full name of the consumer after receiving the first title and ultimate title from the command line. The user has also abbreviated the first title as ‘ f ‘ and the final title as ‘ l ‘.

Example 2:

In this example, the consumer can use the full structure as ‘ first_name ‘ and ‘ last_name ‘ instead of the usage of the brief form as ‘ f ‘ and ‘ l ‘.

import sys                                                   
import getopt                                           # import getopt module           
    
def full_name ( ):   
    first_name = None  
    last_name = None  
    
    argv = sys.argv [ 1: ]   
    
    try:   
        opts , args = getopt.getopt ( argv , " f:l: " ,  [ " first_name = " , " last_name = " ] )   
        
    except:   
        print ( " Error " )   
    
    for opt , arg in opts:   
        if opt in [ ' -f ' , ' --first_name ' ] :   
            first_name = arg   
        elif opt in [ ' -l ' , ' -- last_name ' ] :   
            last_name = arg   
        
    
    print ( first_name + " " + last_name )   
    
full_name ( )   

Output:

The consumer has to bear in mind that the single dash ( ‘ – ‘ ) for quick forms of the arguments and for long varieties of the arguments users should use the double sprint ( ‘ — ‘ ).

Conclusion:

In this article, we have mentioned the getopt() module and its features and their arguments. We have also explained the distinctive enforcing forms with ideal policies in the command line prompt, with well-defined examples.