Python Optparse and Argparse Example

Posted on with tags: python

Argparse module was in Python version 3.2 and up. It superseded optparse module. Inkscape 0.92 extension program file was written many years ago with optparse module. I read several articles trying to understand how to use optparse and argparse modules. An example discussed in this blog post is very helpful.

The article has an example program designed with two options. Run the program on command line with options and arguments shown on that blog, and it shows how optparse module works behind scene.

Following code is a rewrite of the example with argparse. You can execute similar commands shown below and compare the results.

#!/usr/bin/env python3
# This is a version using argparse
# revised by GHZ on 2/2019

import argparse

def main():

    parser = argparse.ArgumentParser(
        usage = 'usage: %(prog)s [options] filename'

    parser.add_argument('-x', '--xhtml',
        action = 'store_true', dest = 'xhtml_flag',
        default = False,
        help = 'create a XHTML template instead of HTML'

    parser.add_argument('-c', '--cssfile',
        action = 'store',
        dest = 'cssfile',
        default = 'style.css',
        help = 'CSS file to link',

    parser.add_argument('filename', nargs='?',  # '*' for multiple files
        action = 'store',
        help = 'the name of file to be processed'

    parser.add_argument('-V', '--version',
        action='version', version='%(prog)s 1.0')

    args = parser.parse_args()

if __name__ == '__main__':

Here are the bash commands to test code.

python -h
python myfile.html
python -x -c mystyle.css myfile.html
python --xhtml --cssfile=mystyle.css myfile.html

The argparse module contains many other options. Here is a link to Python argparse Offical Doc.