Home
Python
getopt Method Example
Updated Mar 28, 2024
Dot Net Perls
Getopt. Python programs can be written to handle command-line arguments, and this makes them more versatile. The code does not need to be changed for different uses.
And with getopt, we have a basic command-line argument parser. The argparse module is more powerful and modern, but getopt is still useful in many programs.
argparse
Example. This program uses the getopt module, and its getopt() method, to handle 4 different command line options. Two of the options, file and int, support an argument.
Step 1 We specify the short argument string. Each option has a character, and options followed by a colon accept an argument.
Step 2 The long arguments are in the same order as the short arguments. For options with arguments, we include the equals sign.
Step 3 We call getopt(), passing the sys.argv slice of all elements past the first one (which is the file name).
Step 4 We loop over the list of tuples returned by getopt(), and we can test the option and an argument if it is present.
for
if
import getopt, sys # Step 1: specify short arguments for getopt, using a colon after arguments that require a value. shortargs = "hf:i:d" # Step 2: specify long arguments, which correspond to the short argument characters. longargs = ["help", "file=", "int=", "debug"] # Step 3: parse command-line arguments with getopt. opts, args = getopt.getopt(sys.argv[1:], shortargs, longargs) # Step 4: loop over all arguments and test them. for opt, arg in opts: if opt == "-d" or opt == "--debug": print("Debug mode enabled") elif opt == "-h" or opt == "--help": print("Help message") elif opt == "-f" or opt == "--file": print(f"File is {arg}") elif opt == "-i" or opt == "--int": print(f"Int is {arg}") incremented = int(arg) + 1 print(f"... Incremented is {incremented}")
python3 program.py --file=bird -i10 -d --help --debug
File is bird Int is 10 ... Incremented is 11 Debug mode enabled Help message Debug mode enabled
Results. In the program, we pass both short and long arguments, and they are all parsed correctly. It is important to note that with the short argument form, we must not include an equals sign.
Summary. While the argparse module is more powerful, and can reduce the amount of code we need to write, optparse can still be valuable. For simpler programs, or legacy programs, it is effective.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 28, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen