Open In App

Getopt module in Python

Last Updated : 26 Jun, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The getopt module is a parser for command-line options based on the convention established by the Unix getopt() function. It is generally used for parsing an argument sequence, such as sys.argv.

This module helps scripts parse command-line arguments in sys.argv. It works similarly to the C getopt() function for parsing command-line parameters.

Syntax

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

Parameters:

  • args: List of arguments to be passed.
  • options: A string of option letters that the script wants to recognize. Options that require an argument should be followed by a colon (:).
  • long_options: A list of strings containing the names of long options. Options that require arguments should be followed by an equal sign (=).

Return Type: returns a tuple consisting of two elements:

  • A list of (option, value) pairs.
  • A list of program arguments left after the option list was stripped.

Example 1: Using Short-Form Options

Parses short options -f and -l for first and last names.

Python
import sys
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 == '-f':
            first_name = arg
        elif opt == '-l':
            last_name = arg
    
    print(first_name + " " + last_name)

full_name()

Output:

Explanation: In this example, the function full_name() prints the full name by accepting the first name and last name from the command line, where 'f' is used for the first name and 'l' for the last name.

Example 2: Using Long-Form Options

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

Python
import sys
import getopt

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:

Note: Use single dash (-) for short options (e.g., -f) and double dash (--) for long options (e.g., --first_name). Long options requiring arguments must end with = without spaces.


Practice Tags :

Similar Reads