Home
Map
getopt Method ExampleUse the getopt module to access command-line arguments. Handle options and arguments.
Python
This page was last reviewed on Mar 28, 2024.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 28, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.