Optparse module in Python
Last Updated :
30 Nov, 2022
Optparse module makes easy to write command-line tools. It allows argument parsing in the python program.
- optparse make it easy to handle the command-line argument.
- It comes default with python.
- It allows dynamic data input to change the output
Code: Creating an OptionParser object.
Python3
import optparse
parser = optparse.OptionParser()
Defining options:
It should be added one at a time using the add_option(). Each Option instance represents a set of synonymous command-line option string.
Way to create an Option instance are:
OptionParser.add_option(option)
OptionParser.add_option(*opt_str, attr=value, ...)
To define an option with only a short option string:
parser.add_option("-f", attr=value, ....)
And to define an option with only a long option string:
parser.add_option("--foo", attr=value, ....)
Standard Option Actions:
- "store": store this option’s argument (default).
- "store_const": store a constant value.
- "store_true": store True.
- "store_false": store False.
- "append": append this option’s argument to a list.
- "append_const": append a constant value to a list.
Standard Option Attributes:
- Option.action: (default: "store")
- Option.type: (default: "string")
- Option.dest: (default: derived from option strings)
- Option.default: The value to use for this option’s destination if the option is not seen on the command line.
Here’s an example of using optparse module in a simple script:
Python3
# import OptionParser class
# from optparse module.
from optparse import OptionParser
# create a OptionParser
# class object
parser = OptionParser()
# add options
parser.add_option("-f", "--file",
dest = "filename",
help = "write report to FILE",
metavar = "FILE")
parser.add_option("-q", "--quiet",
action = "store_false",
dest = "verbose", default = True,
help = "don't print status messages to stdout")
(options, args) = parser.parse_args()
With these few lines of code, users of your script can now do the “usual thing” on the command-line, for example:
<yourscript> --file=outfile -q
Lets, understand with an example:
Code: Writing python script for print table of n.
Python3
# import optparse module
import optparse
# define a function for
# table of n
def table(n, dest_cheak):
for i in range(1,11):
tab = i*n
if dest_cheak:
print(tab)
return tab
# define a function for
# adding options
def Main():
# create OptionParser object
parser = optparse.OptionParser()
# add options
parser.add_option('-n', dest = 'num',
type = 'int',
help = 'specify the n''th table number to output')
parser.add_option('-o', dest = 'out',
type = 'string',
help = 'specify an output file (Optional)')
parser.add_option("-a", "--all",
action = "store_true",
dest = "print",
default = False,
help = "print all numbers up to N")
(options, args) = parser.parse_args()
if (options.num == None):
print (parser.usage)
exit(0)
else:
number = options.num
# function calling
result = table(number, options.print)
print ("The " + str(number)+ "th table is " + str(result))
if (options.out != None):
# open a file in append mode
f = open(options.out,"a")
# write in the file
f.write(str(result) + '\n')
# Driver code
if __name__ == '__main__':
# function calling
Main()
Output:
python file_name.py -n 4

python file_name.py -n 4 -o

file.txt created

python file_name.py -n 4 -a

For knowing more about this module click here.
Similar Reads
Platform Module in Python Platform module in Python is a built-in library that provides a portable way to access detailed information about the underlying platform (hardware and operating system) on which your Python program is running. This can include data such as the OS name and version, machine type, processor info and P
3 min read
Python Module Index Python has a vast ecosystem of modules and packages. These modules enable developers to perform a wide range of tasks without taking the headache of creating a custom module for them to perform a particular task. Whether we have to perform data analysis, set up a web server, or automate tasks, there
4 min read
Pyscaffold module in Python Starting off with a Python project is usually quite complex and complicated as it involves setting up and configuring some files. This is where Pyscaffold comes in. It is a tool to set up a new python project, is very easy to use and sets up your project in less than 10 seconds! To use Pyscaffold, G
4 min read
Python Modules Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Basics Of Python Modules A library refers to a collection of modules that together cater to a specific type of needs or application. Module is a file(.py file) containing variables, class definitions statements, and functions related to a particular task. Python modules that come preloaded with Python are called standard li
3 min read
Built-in Modules in Python Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include Python built-in modules and ext
9 min read
External Modules in Python Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include built-in modules and external m
5 min read
Import module in Python In Python, modules allow us to organize code into reusable files, making it easy to import and use functions, classes, and variables from other scripts. Importing a module in Python is similar to using #include in C/C++, providing access to pre-written code and built-in libraries. Pythonâs import st
3 min read
__future__ Module in Python __future__ module is a built-in module in Python that is used to inherit new features that will be available in the new Python versions.. This module includes all the latest functions which were not present in the previous version in Python. And we can use this by importing the __future__ module. I
4 min read
Inspect Module in Python The inspect module in Python is useful for examining objects in your code. Since Python is an object-oriented language, this module helps inspect modules, functions and other objects to better understand their structure. It also allows for detailed analysis of function calls and tracebacks, making d
4 min read