Hello geeks and welcome in this article, we will cover python getopt. Along with that, for an overall better understanding, we will look at its syntax and parameter. Then we will see a couple of examples to understand the topic better. But at first, let us try to get a brief understanding of the function through its definition.
Like NumPy and Matplotlib, getopt is also a module of python. This module is very similar to the getopt function of the C language. This function is used for parsing command line parameters. The Python getopt function’s primary function is to parse command-line options and parameter lists. As we move ahead in this article, things will become a lot clearer. In the next section, we will look at the syntax.
Syntax
getopt.getopt()
This is the general syntax for our function. Now let us look at the various parameters associated with it.
Parameters
1. args:
This parameter represents the type of arguments to be passed through.
2. options:
This parameter represents the string of option letters that the script wants to recognize.
Example:
import getopt
print getopt.getopt(['-a', '-bval', '-c', 'val'], 'ab:c:')
3. Long_options:
This parameter represents a list of string with the name of long options.
Example:
import getopt
print getopt.getopt([ '--noarg', '--witharg', 'val', '--witharg2=another' ],
'',
[ 'noarg', 'witharg=', 'witharg2=' ])
Return Type:
On completion of the program, it returns the value consisting of 2 elements. The first type is the list of pairs. Whereas the second is the list of program arguments left after the option is was removed.
How to install Python getopt?
There is no need to install the getopt module externally. It’s an inbuilt module that is pre-included in Python along with it. Just like any other inbuilt module, you can use it by –
import getopt
Python getopt Examples
Now we are done with all the theory part. We have covered its syntax and parameters in detail. It’s time to discuss various examples that will help understand the topic better. Let us start with an elementary level example, and as we move ahead, we will gradually increase the level of example.
1. Country Name
import sys
import getopt
def country_name():
state_name = None
country_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']:
state_name = arg
elif opt in ['-l']:
country_name = arg
print("{0}{1}".format(state_name, country_name))
country_name()
From this particular example, our goal is to print out state and country by taking input from the user in the command line. To do so, first, we need to import 2 modules, namely sys and getopt. After this, I have defined a function and name it as country name. Later on, we have used a For loop and print statement to get the desired output. In this case, if you don’t input the values in the terminal, it will return None None as output.
2. Date and month
import sys
import getopt
def date_month():
start_date = None
start_month = None
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "s:e:", ["start_date=", "start_month="])
except getopt.GetoptError as err:
print(err)
for opt, arg in opts:
if opt in ["-s", "--start_date"]:
start_date = arg
elif opt in ["-e", "--start_month"]:
start_month = arg
print('start_date: {}'.format(start_date))
print('start_month: {}'.format(start_month))
date_month()
A similar example of what we have already discussed above. The goal of this function is to program is to print out the date and month. The whole procedure is similar to what we followed in the first example.
Python getopt long options
Long options are the set of arguments that are used in the ‘–option=’ format. These options are usually optional arguments. To use long options you have to specify an empty string in the getopt() parameters. This is forces the code to only accept long options.
Code (test.py):
import sys
import getopt
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "", ["option="])
except getopt.GetoptError as err:
print(err)
for opt, arg in opts:
print(opt, arg)
Terminal:
python .\test.py --option=hello
Output:
--option hello
getopt Multiple arguments
This function, in particular, takes 3 arguments. The first argument is the sequence of arguments to be parsed. Followed by this, the second argument takes is the option definition string for the single-character option. Then the 3rd argument takes the long option names. Long type options can be more than just a single character. If the long option name requires an argument, its name should have a suffix of “=. suffix”
Difference between getopt vs argparse
In this section, we will discuss the fundamental difference between these 2 Python modules. Both of the Python modules are used to parse the command-line argument. As we have already discussed, getopt in detail now let us try to get a brief understanding of the argparse. As discussed earlier, both the modules have the same function. But it recommended using over the getopt module. The reason being it is less complicated. Also, it requires fewer lines of code to execute the same program when compared to getopt.
Also Read
- Best 8 Career Option With Python To Earn Massive
- Python map Function Explanation and Examples
- Ways to Achieve Multiple Constructors in Python
- Python dateutil Module: Explanation and Examples
Conclusion
This article covers Python getopt. Besides that, we have also looked at its syntax and parameters. For better understanding, we looked at a couple of examples. We varied the syntax and looked at the output for each case. In the end, we can conclude that Python getopt is a function primary job is to parse the command-line option.
I hope this article was able to clear all doubts. But in case you have any unsolved queries feel free to write them below in the comment section. Done reading this; why not read about Matplotlib Font next.