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.
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.
short
argument string
. Each option has a character, and options followed by a colon accept an argument.short
arguments. For options with arguments, we include the equals sign.getopt()
, passing the sys.argv
slice of all elements past the first one (which is the file name).getopt()
, and we can test the option and an argument if it is present.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 --debugFile is bird Int is 10 ... Incremented is 11 Debug mode enabled Help message Debug mode enabled
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.
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.