Created
June 27, 2012 14:31
-
-
Save avihut/3004424 to your computer and use it in GitHub Desktop.
optparse decorator
This file contains hidden or 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
from optparse import OptionParser, Option | |
from functools import wraps | |
my_parser = OptionParser(usage = "Usage: %prog [options]") | |
approve_option = Option("-a", "--approve", default = False, action = "store_true", \ | |
help = "Must be provided along with disruptive options.") | |
class optparse_option(object): | |
# Can also accept 'ask_for_approval' argument. By default it's False. | |
def __init__(self, parser, *args, **kwargs): | |
self.parser = parser | |
self.args = args | |
self.kwargs = kwargs | |
self.add_approve_option() | |
self.should_ask_for_approval() | |
def add_approve_option(self): | |
if not approve_option in self.parser.option_list: | |
self.parser.add_option(approve_option) | |
def add_ask_for_approval_help(self): | |
if "help" in self.kwargs: | |
self.kwargs["help"] += " This options is disruptive and requires explicit approval to perform." | |
def should_ask_for_approval(self): | |
if 'ask_for_approval' in self.kwargs: | |
self.ask_for_approval = self.kwargs['ask_for_approval'] | |
del self.kwargs['ask_for_approval'] | |
self.add_ask_for_approval_help() | |
else: | |
self.ask_for_approval = False | |
def is_approval_provided(self): | |
approve_reps = str(approve_option).split('/') | |
import sys | |
for rep in approve_reps: | |
if rep in sys.argv: | |
return True | |
return False | |
def __call__(self, func): | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
if self.ask_for_approval: | |
if self.is_approval_provided(): | |
return func(*args, **kwargs) | |
else: | |
print "Approval must be provided for this option. Please run this option again with -a or " \ | |
"--approve." | |
self.kwargs['action'] = "callback" | |
self.kwargs["callback"] = wrapper | |
self.parser.add_option(*self.args, **self.kwargs) | |
return wrapper | |
@optparse_option(my_parser, "-f", "--funky", default = False, help = "Run a funky function.", ask_for_approval = True) | |
def funky_option(option, opt, value, parser): | |
print "Funky was run." | |
@optparse_option(my_parser, "-s", "--second", default = False, help = "Run second funk!") | |
def second_funk(option, opt, value, parser): | |
print "Second funk!" | |
def main(): | |
options, args = my_parser.parse_args() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment