Created
October 14, 2011 18:48
-
-
Save coffindragger/1287953 to your computer and use it in GitHub Desktop.
Base class for creating commandline python scripts using optparse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyScript(OptionParserScript): | |
usage = "Usage: %prog <command> [arguments]" | |
options = { | |
('-v','--verbose'): {'help':"Be verbose", 'action': 'store_true', 'default': False}, | |
} | |
def main(self, *args, **kwargs): | |
import pprint | |
pprint.pprint(args) | |
pprint.pprint(kwargs) | |
return 0 | |
if __name__ == '__main__': | |
script = MyScript() | |
sys.exit(script()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OptionParserScript(object): | |
def __call__(self, *args, **kwargs): | |
parser = optparse.OptionParser(getattr(self,'usage',None)) | |
opts = getattr(self, 'options', None) | |
if opts is not None: | |
for opts_args, opts_kwargs in opts.items(): | |
parser.add_option(*opts_args, **opts_kwargs) | |
parsed_options, parsed_args = parser.parse_args() | |
return self.main(*parsed_args, **vars(parsed_options)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment