Created
November 19, 2018 22:10
-
-
Save shreyb/d4639b2b88103d5ca3559d95d6db94b7 to your computer and use it in GitHub Desktop.
Quick mockup for checking for doubled command line options
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
from optparse import Option, OptionParser | |
# Adapted from https://stackoverflow.com/questions/23032514/argparse-disable-same-argument-occurences and optparse docs | |
class MyOption(Option): | |
ACTIONS = Option.ACTIONS + ("unique_store",) | |
STORE_ACTIONS = Option.STORE_ACTIONS + ("unique_store",) | |
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("unique_store",) | |
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("unique_store",) | |
def take_action(self, action, dest, opt, value, values, parser): | |
if action == 'unique_store': | |
if values.ensure_value(dest, None) is not None: | |
parser.error(opt + " appears more than once. Please try again with only one " + opt + " option given") | |
else: | |
setattr(values, dest, value) | |
else: | |
Option.take_action( | |
self, action, dest, opt, value, values, parser) | |
def main(): | |
parser = OptionParser(option_class=MyOption) | |
parser.add_option("-t", "--test", dest="test", action="store") | |
parser.add_option("-u", "--unique", dest="unique_var", action="unique_store") | |
(opts, args) = parser.parse_args() | |
print opts.test | |
print opts.unique_var | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment