The getopt module in Python provides a way to parse command-line options and arguments. It is a simpler alternative to the more powerful argparse module, and it is similar in functionality to the C library's getopt() function.
Table of Contents
- Introduction
- Key Functions
getopt
- Examples
- Parsing Command-Line Options
- Handling Both Short and Long Options
- Using Default Values
- Real-World Use Case
- Conclusion
- References
Introduction
The getopt module is used to parse command-line options and arguments. It provides a straightforward way to handle options and arguments, making it suitable for simple command-line scripts.
Key Functions
getopt
Parses command-line options and arguments.
import getopt
import sys
opts, args = getopt.getopt(sys.argv[1:], 'ho:v', ['help', 'output=', 'verbose'])
sys.argv[1:]: The list of command-line arguments passed to the script, excluding the script name.'ho:v': Short option definitions. Options that require an argument are followed by a colon (:).['help', 'output=', 'verbose']: Long option definitions. Options that require an argument are followed by an equals sign (=).
Examples
Parsing Command-Line Options
import getopt
import sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'ho:v', ['help', 'output=', 'verbose'])
except getopt.GetoptError as err:
print(err)
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o in ('-h', '--help'):
print('Usage: script.py -o <outputfile> -v')
sys.exit()
elif o in ('-o', '--output'):
output = a
elif o in ('-v', '--verbose'):
verbose = True
else:
assert False, 'Unhandled option'
print(f'Output: {output}')
print(f'Verbose: {verbose}')
if __name__ == '__main__':
main()
Command Line:
$ python script.py -o result.txt -v
Output:
Output: result.txt
Verbose: True
Handling Both Short and Long Options
import getopt
import sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'hi:o:', ['help', 'input=', 'output='])
except getopt.GetoptError as err:
print(err)
sys.exit(2)
inputfile = None
outputfile = None
for o, a in opts:
if o in ('-h', '--help'):
print('Usage: script.py -i <inputfile> -o <outputfile>')
sys.exit()
elif o in ('-i', '--input'):
inputfile = a
elif o in ('-o', '--output'):
outputfile = a
else:
assert False, 'Unhandled option'
print(f'Input file: {inputfile}')
print(f'Output file: {outputfile}')
if __name__ == '__main__':
main()
Command Line:
$ python script.py -i input.txt --output=output.txt
Output:
Input file: input.txt
Output file: output.txt
Using Default Values
import getopt
import sys
def main():
inputfile = 'default_input.txt'
outputfile = 'default_output.txt'
try:
opts, args = getopt.getopt(sys.argv[1:], 'hi:o:', ['help', 'input=', 'output='])
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o in ('-h', '--help'):
print('Usage: script.py -i <inputfile> -o <outputfile>')
sys.exit()
elif o in ('-i', '--input'):
inputfile = a
elif o in ('-o', '--output'):
outputfile = a
else:
assert False, 'Unhandled option'
print(f'Input file: {inputfile}')
print(f'Output file: {outputfile}')
if __name__ == '__main__':
main()
Command Line:
$ python script.py
Output:
Input file: default_input.txt
Output file: default_output.txt
Real-World Use Case
Batch Processing Script
import getopt
import sys
def process_files(inputfile, outputfile):
print(f'Processing input file: {inputfile}')
print(f'Saving results to: {outputfile}')
def main():
inputfile = None
outputfile = None
try:
opts, args = getopt.getopt(sys.argv[1:], 'hi:o:', ['help', 'input=', 'output='])
except getopt.GetoptError as err:
print(err)
sys.exit(2)
for o, a in opts:
if o in ('-h', '--help'):
print('Usage: script.py -i <inputfile> -o <outputfile>')
sys.exit()
elif o in ('-i', '--input'):
inputfile = a
elif o in ('-o', '--output'):
outputfile = a
else:
assert False, 'Unhandled option'
if inputfile and outputfile:
process_files(inputfile, outputfile)
else:
print('Usage: script.py -i <inputfile> -o <outputfile>')
sys.exit(2)
if __name__ == '__main__':
main()
Command Line:
$ python script.py -i data.txt -o result.txt
Output:
Processing input file: data.txt
Saving results to: result.txt
Conclusion
The getopt module in Python provides a simple way to parse command-line options and arguments. It is useful for basic scripts and when you need to quickly add command-line argument parsing to a program. For more complex command-line interfaces, consider using the argparse module.
References
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment