Python: optparse

I'm working on a library that can override the built-in Python library optparse. For those who don't know, optparse.OptionParser is a class which handles arguments passed to you program at the command line. It's quite powerful, a quick count shows that I have almost 50 utility programs that I wrote that use it. I want to leverage this ability and be able to put a pretty front end on these programs. My idea is to replace optparse with my own class which throws up a user interface showing the options as controls.
Basically, I plan to call "wxoptparse mygprog" which would load up myprog.py and look at the options available and bring up a dialog box (in wxPython) showing what the options are. This was far easier than I had ever imagined. Here's the crux of the code:
import optparse, wx

# my class inherits from OptionParser
class wxOptParser(optparse.OptionParser):
# Override this method
def parse_args(self, args=None, values=None):
# Stuff snipped out here
app.MainLoop()
# After quitting the loop we'll return the values
return (self.options, self.args)

optparse.OptionParser = wxOptParser # Replace the original with mine!
execfile(strFilename) # Run the program passed in "normally"

That's all there is to it. In the end I'll store the previously used values in an xml file so this will be even more useful. Another idea is to capture the output in a window as well, with error handling, etc. What really makes this solution interesting is that you can have a solution that's both graphical and command line driven.

Comments

Popular posts from this blog

Shortest Sudoku solver in Python

Seven Segment Display in Inkscape

Dot to Png