🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment