Command-line argument parsing is essential when building flexible programs. Python's getopt module provides a way to handle both short-form and long-form options efficiently.
Understanding Command Line Arguments
When executing a Python script, all arguments passed after the script name are stored in sys.argv. This list contains the script name itself as the first element, followed by any additional arguments separated by spaces.
#!/usr/bin/env python3
import sys
print(sys.argv)
Running python get.py -o t --help cmd file1 file2 produces:
['get.py', '-o', 't', '--help', 'cmd', 'file1', 'file2']
Short and Long Options
Two standard option formats exist in Unix-like systems:
Short options use a single hyphen followed by a single letter. They can be combined and may have attached values:
-i 127.0.0.1
-p 80
-oa
-obbbb
-o "a b"
Long options use double hyphens followed by a word. Rqeuired values are attached using an equals sign:
--ip=127.0.0.1
--port=80
--help=file1
The getopt Function
getopt.getopt(args, shortopts, longopts=[])
args: Typicallysys.argv[1:](excludes script name)shortopts: String defining short options (colons indicate required values)longopts: List defining long options (equals signs indicate required values)
Practical Example
import sys
import getopt
def show_help():
print("Usage: python script.py -h -i <address> -p <port>")
sys.exit()
try:
opts, remaining = getopt.getopt(
sys.argv[1:],
"hi:p:",
["help", "ip=", "port="]
)
except getopt.GetoptError:
sys.exit(1)
for opt, arg in opts:
if opt in ("-h", "--help"):
show_help()
elif opt in ("-i", "--ip"):
print(f"IP address: {arg}")
elif opt in ("-p", "--port"):
print(f"Port number: {arg}")
Short options parsing rules:
hwith no colon: takes no argumenti:andp:with colons: require an argument
Long options parsing rules:
helpwith no equals: takes no argumentip=andport=with equals signs: require an argument
Understanding Return Values
The function returns a tuple containing two elements:
-
opts: List of tuples with parsed option pairs. For example:[('-i', '127.0.0.1'), ('-p', '80')] -
remaining: List of positional arguments that lack option prefixes. For example:['55', '66']
When defining options, parameters requiring values should precede those that do not. The parser processes options in the order they appear in the command line, and unrecognized options trigger a GetoptError exception that should be handled appropriately.