# Python getopt Module: A – Z Guide

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.

Contents

## 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.
{"ft_lang_label":"__label__en","ft_lang_prob":0.7577555,"math_prob":0.6214313,"size":5922,"snap":"2021-31-2021-39","text_gpt3_token_len":1328,"char_repetition_ratio":0.13180128,"word_repetition_ratio":0.053014554,"special_character_ratio":0.23269166,"punctuation_ratio":0.1480851,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9832059,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-09-20T18:16:33Z\",\"WARC-Record-ID\":\"<urn:uuid:499a2f3e-e987-45a8-84b3-278ab0e92ecd>\",\"Content-Length\":\"124107\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:f0e75919-de7c-481c-ad65-f0692cb8cc2d>\",\"WARC-Concurrent-To\":\"<urn:uuid:7e5fb490-26cd-4b4f-9a3c-5c283fc077be>\",\"WARC-IP-Address\":\"172.67.132.234\",\"WARC-Target-URI\":\"https://www.pythonpool.com/python-getopt/\",\"WARC-Payload-Digest\":\"sha1:RLRNDPFSCJFCWRYQ5ZTSMU3DR3GXIGFI\",\"WARC-Block-Digest\":\"sha1:EC7GBPPDM5S456WQY3O2GA2UKOXKHD2G\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-39/CC-MAIN-2021-39_segments_1631780057083.64_warc_CC-MAIN-20210920161518-20210920191518-00286.warc.gz\"}"}