Python optparse.make_option() Examples

The following are 30 code examples of optparse.make_option(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module optparse , or try the search function .
Example #1
Source File: git_p4.py    From python-zulip-api with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        P4Sync.__init__(self)
        self.description = "Creates a new git repository and imports from Perforce into it"
        self.usage = "usage: %prog [options] //depot/path[@revRange]"
        self.options += [
            optparse.make_option("--destination", dest="cloneDestination",
                                 action='store', default=None,
                                 help="where to leave result of the clone"),
            optparse.make_option("-/", dest="cloneExclude",
                                 action="append", type="string",
                                 help="exclude depot path"),
            optparse.make_option("--bare", dest="cloneBare",
                                 action="store_true", default=False),
        ]
        self.cloneDestination = None
        self.needsGit = False
        self.cloneBare = False

    # This is required for the "append" cloneExclude action 
Example #2
Source File: jsonschema.py    From pyang-json-schema-plugin with Apache License 2.0 6 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option('--jsonschema-debug',
                                 dest='schema_debug',
                                 action="store_true",
                                 help='JSON Schema debug'),
            optparse.make_option('--jsonschema-path',
                                 dest='schema_path',
                                 help='JSON Schema path'),
            optparse.make_option('--jsonschema-title',
                                 dest='schema_title',
                                 help='JSON Schema title'),
            ]

        group = optparser.add_option_group("JSON Schema-specific options")
        group.add_options(optlist) 
Example #3
Source File: yang.py    From pyang with ISC License 6 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--yang-canonical",
                                 dest="yang_canonical",
                                 action="store_true",
                                 help="Print in canonical order"),
            optparse.make_option("--yang-remove-unused-imports",
                                 dest="yang_remove_unused_imports",
                                 action="store_true"),
            optparse.make_option("--yang-remove-comments",
                                 dest="yang_remove_comments",
                                 action="store_true"),
            optparse.make_option("--yang-line-length",
                                 type="int",
                                 dest="yang_line_length",
                                 help="Maximum line length"),
            ]
        g = optparser.add_option_group("YANG output specific options")
        g.add_options(optlist) 
Example #4
Source File: sample-xml-skeleton.py    From pyang with ISC License 6 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--sample-xml-skeleton-doctype",
                                 dest="doctype",
                                 default="data",
                                 help="Type of sample XML document " +
                                 "(data or config)."),
            optparse.make_option("--sample-xml-skeleton-defaults",
                                 action="store_true",
                                 dest="sample_defaults",
                                 default=False,
                                 help="Insert leafs with defaults values."),
            optparse.make_option("--sample-xml-skeleton-annotations",
                                 action="store_true",
                                 dest="sample_annots",
                                 default=False,
                                 help="Add annotations as XML comments."),
            optparse.make_option("--sample-xml-skeleton-path",
                                 dest="sample_path",
                                 help="Subtree to print"),
        ]
        g = optparser.add_option_group(
            "Sample-xml-skeleton output specific options")
        g.add_options(optlist) 
Example #5
Source File: lint.py    From pyang with ISC License 6 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--lint",
                                 dest="lint",
                                 action="store_true",
                                 help="Validate the module(s) according to " \
                                 "RFC 8407rules."),
            optparse.make_option("--lint-namespace-prefix",
                                 dest="lint_namespace_prefixes",
                                 default=[],
                                 action="append",
                                 help="Validate that the module's namespace " \
                                     "matches one of the given prefixes."),
            optparse.make_option("--lint-modulename-prefix",
                                 dest="lint_modulename_prefixes",
                                 default=[],
                                 action="append",
                                 help="Validate that the module's name " \
                                     "matches one of the given prefixes."),
            optparse.make_option("--lint-ensure-hyphenated-names",
                                 dest="lint_ensure_hyphenated_names",
                                 action="store_true",
                                 help="No upper case and underscore in names."),
            ]
        optparser.add_options(optlist) 
Example #6
Source File: jstree.py    From pyang with ISC License 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--jstree-no-path",
                                 dest="jstree_no_path",
                                 action="store_true",
                                 help="""Do not include paths to make
                                       page less wide"""),
            optparse.make_option("--jstree-path",
                                 dest="jstree_path",
                                 help="Subtree to print"),
            ]

        g = optparser.add_option_group("JSTree output specific options")
        g.add_options(optlist) 
Example #7
Source File: _base.py    From django-dbbackup with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.option_list = self.base_option_list + self.option_list
        if django.VERSION < (1, 10):
            options = tuple([optparse_make_option(*_args, **_kwargs)
                             for _args, _kwargs in self.option_list])
            self.option_list = options + BaseCommand.option_list
        super(BaseDbBackupCommand, self).__init__(*args, **kwargs) 
Example #8
Source File: git_p4.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        Command.__init__(self)
        self.options = [
                optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
        ]
        self.importLabels = False
        self.description = ("Fetches the latest revision from perforce and "
                            + "rebases the current work (branch) against it") 
Example #9
Source File: git_p4.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        Command.__init__(self)
        P4UserMap.__init__(self)
        self.options = [
                optparse.make_option("--origin", dest="origin"),
                optparse.make_option("-M", dest="detectRenames", action="store_true"),
                # preserve the user, requires relevant p4 permissions
                optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
                optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
                optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
                optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
                optparse.make_option("--conflict", dest="conflict_behavior",
                                     choices=self.conflict_behavior_choices),
                optparse.make_option("--branch", dest="branch"),
        ]
        self.description = "Submit changes from git to the perforce depot."
        self.usage += " [name of git branch to submit into perforce depot]"
        self.origin = ""
        self.detectRenames = False
        self.preserveUser = gitConfigBool("git-p4.preserveUser")
        self.dry_run = False
        self.prepare_p4_only = False
        self.conflict_behavior = None
        self.isWindows = (platform.system() == "Windows")
        self.exportLabels = False
        self.p4HasMoveCommand = p4_has_move_command()
        self.branch = None 
Example #10
Source File: git_p4.py    From python-zulip-api with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        Command.__init__(self)
        self.options = [
            optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
        ]
        self.description = "A tool to debug the multi-branch import. Don't use :)"
        self.rollbackLocalBranches = False 
Example #11
Source File: run_gunicorn.py    From Flask-P2P with MIT License 5 votes vote down vote up
def make_options():
    opts = [
        make_option('--adminmedia', dest='admin_media_path', default='',
        help='Specifies the directory from which to serve admin media.')
    ]

    g_settings = make_settings(ignore=("version"))
    keys = g_settings.keys()
    for k in keys:
        if k in ('pythonpath', 'django_settings',):
            continue

        setting = g_settings[k]
        if not setting.cli:
            continue

        args = tuple(setting.cli)

        kwargs = {
            "dest": setting.name,
            "metavar": setting.meta or None,
            "action": setting.action or "store",
            "type": setting.type or "string",
            "default": None,
            "help": "%s [%s]" % (setting.short, setting.default)
        }
        if kwargs["action"] != "store":
            kwargs.pop("type")

        opts.append(make_option(*args, **kwargs))

    return tuple(opts) 
Example #12
Source File: omni.py    From pyang with ISC License 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--omni-path",
                                 dest="omni_tree_path",
                                 help="Subtree to print"),
            ]
        g = optparser.add_option_group("OmniGraffle output specific options")
        g.add_options(optlist) 
Example #13
Source File: ietf.py    From pyang with ISC License 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--ietf",
                                 dest="ietf",
                                 action="store_true",
                                 help="Validate the module(s) according to " \
                                 "IETF rules."),
            optparse.make_option("--ietf-help",
                                 dest="ietf_help",
                                 action="store_true",
                                 help="Print help on the IETF checks and exit"),
            ]
        optparser.add_options(optlist) 
Example #14
Source File: ieee.py    From pyang with ISC License 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--ieee",
                                 dest="ieee",
                                 action="store_true",
                                 help="Validate the module(s) according to " \
                                 "IEEE rules."),
            ]
        optparser.add_options(optlist) 
Example #15
Source File: mef.py    From pyang with ISC License 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--mef",
                                 dest="mef",
                                 action="store_true",
                                 help="Validate the module(s) according to " \
                                 "MEF rules."),
            ]
        optparser.add_options(optlist) 
Example #16
Source File: depend.py    From pyang with ISC License 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--depend-target",
                                 dest="depend_target",
                                 help="Makefile rule target"),
            optparse.make_option("--depend-no-submodules",
                                 dest="depend_no_submodules",
                                 action="store_true",
                                 help="Do not generate dependencies for " \
                                 "included submodules"),
            optparse.make_option("--depend-from-submodules",
                                 dest="depend_from_submodules",
                                 action="store_true",
                                 help="Generate dependencies from " \
                                 "included submodules"),
            optparse.make_option("--depend-recurse",
                                 dest="depend_recurse",
                                 action="store_true",
                                 help="Generate dependencies to all " \
                                     "imports, recursively"),
            optparse.make_option("--depend-extension",
                                 dest="depend_extension",
                                 help="YANG module file name extension"),
            optparse.make_option("--depend-include-path",
                                 dest="depend_include_path",
                                 action="store_true",
                                 help="Include file path in the prerequisites"),
            optparse.make_option("--depend-ignore-module",
                                 dest="depend_ignore",
                                 default=[],
                                 action="append",
                                 help="(sub)module to ignore in the" \
                                     " prerequisites.  This option can be" \
                                     " given multiple times."),
            ]
        g = optparser.add_option_group("Depend output specific options")
        g.add_options(optlist) 
Example #17
Source File: sid.py    From pyang with ISC License 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--sid-help",
                                 dest="sid_help",
                                 action="store_true",
                                 help="Print help on automatic SID generation"),
            optparse.make_option("--sid-generate-file",
                                 action="store",
                                 type="string",
                                 dest="generate_sid_file",
                                 help="Generate a .sid file."),
            optparse.make_option("--sid-update-file",
                                 action="store",
                                 type="string",
                                 dest="update_sid_file",
                                 help="Generate a .sid file based on a previous .sid file."),
            optparse.make_option("--sid-check-file",
                                 action="store",
                                 type="string",
                                 dest="check_sid_file",
                                 help="Check the consistency between a .sid file "
                                 "and the .yang file(s)."),
            optparse.make_option("--sid-list",
                                 action="store_true",
                                 dest="list_sid",
                                 help="Print the list of SID."),
            optparse.make_option("--sid-registration-info",
                                 action="store_true",
                                 dest="sid_registration_info",
                                 help="Print the information required by the SID registry."),
            optparse.make_option("--sid-extra-range",
                                 action="store",
                                 type="string",
                                 dest="extra_sid_range",
                                 help="Add an extra SID range during a .sid file update."),
            ]

        g = optparser.add_option_group("SID file specific options")
        g.add_options(optlist) 
Example #18
Source File: capability.py    From pyang with ISC License 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--capability-entity",
                                 dest="capa_entity",
                                 action="store_true",
                                 default=False,
                                 help="Write ampersands as XML entity")
            ]
        g = optparser.add_option_group("Capability output specific options")
        g.add_options(optlist) 
Example #19
Source File: dsdl.py    From pyang with ISC License 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--dsdl-no-documentation",
                                 dest="dsdl_no_documentation",
                                 action="store_true",
                                 default=False,
                                 help="No output of DTD compatibility"
                                 " documentation annotations"),
            optparse.make_option("--dsdl-no-dublin-core",
                                 dest="dsdl_no_dublin_core",
                                 action="store_true",
                                 default=False,
                                 help="No output of Dublin Core"
                                 " metadata annotations"),
            optparse.make_option("--dsdl-record-defs",
                                 dest="dsdl_record_defs",
                                 action="store_true",
                                 default=False,
                                 help="Record all top-level defs"
                                 " (even if not used)"),
            optparse.make_option("--dsdl-lax-yang-version",
                                 dest="dsdl_lax_yang_version",
                                 action="store_true",
                                 default=False,
                                 help="Try to translate modules with "
                                 "unsupported YANG versions (use at own risk)"),
            ]
        g = optparser.add_option_group("Hybrid DSDL schema "
                                       "output specific options")
        g.add_options(optlist) 
Example #20
Source File: yin.py    From pyang with ISC License 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--yin-canonical",
                                 dest="yin_canonical",
                                 action="store_true",
                                 help="Print in canonical order"),
            optparse.make_option("--yin-pretty-strings",
                                 dest="yin_pretty_strings",
                                 action="store_true",
                                 help="Pretty print strings"),
            ]
        g = optparser.add_option_group("YIN output specific options")
        g.add_options(optlist) 
Example #21
Source File: _base.py    From django-test-without-migrations with MIT License 5 votes vote down vote up
def __init__(self):
        super(CommandMixin, self).__init__()

        # Optparse was deprecated on 1.8
        # So we only define option_list for Django 1.7
        if DJANGO_VERSION < (1, 8):
            self.option_list = super(CommandMixin, self).option_list + (
                optparse.make_option(
                    '-n',
                    '--nomigrations',
                    action='store_true',
                    dest='nomigrations',
                    default=False,
                    help=HELP),
            ) 
Example #22
Source File: run_gunicorn.py    From jbox with MIT License 5 votes vote down vote up
def make_options():
    opts = [
        make_option('--adminmedia', dest='admin_media_path', default='',
        help='Specifies the directory from which to serve admin media.')
    ]

    g_settings = make_settings(ignore=("version"))
    keys = g_settings.keys()
    for k in keys:
        if k in ('pythonpath', 'django_settings',):
            continue

        setting = g_settings[k]
        if not setting.cli:
            continue

        args = tuple(setting.cli)

        kwargs = {
            "dest": setting.name,
            "metavar": setting.meta or None,
            "action": setting.action or "store",
            "type": setting.type or "string",
            "default": None,
            "help": "%s [%s]" % (setting.short, setting.default)
        }
        if kwargs["action"] != "store":
            kwargs.pop("type")

        opts.append(make_option(*args, **kwargs))

    return tuple(opts) 
Example #23
Source File: cxml.py    From yang-explorer with Apache License 2.0 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--cxml-help",
                                 dest="cxml_help",
                                 action="store_true",
                                 help="Print help on cxml symbols and exit"),
        ]
        g = optparser.add_option_group("CXML output specific options")
        g.add_options(optlist) 
Example #24
Source File: pyimport.py    From yang-explorer with Apache License 2.0 5 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--pyimport-help",
                                 dest="pyimport_help",
                                 action="store_true",
                                 help="Print help on PyImport and exit"),
            ]
        g = optparser.add_option_group("PyImport output specific options")
        g.add_options(optlist) 
Example #25
Source File: cmd2plus.py    From OpenTrader with GNU Lesser General Public License v3.0 4 votes vote down vote up
def options(option_list, arg_desc="arg", usage=None):
    '''Used as a decorator and passed a list of optparse-style options,
       alters a cmd2 method to populate its ``opts`` argument from its
       raw text argument.

       Example: transform
       def do_something(self, arg):

       into
       @options([make_option('-q', '--quick', action="store_true",
                 help="Makes things fast")],
                 "source dest")
       def do_something(self, arg, opts):
           if opts.quick:
               self.fast_button = True
       '''
    global lOPTIONS_DEFINED
    if not isinstance(option_list, list):
        option_list = [option_list]
    for opt in option_list:
        lOPTIONS_DEFINED.append(pyparsing.Literal(opt.get_opt_string()))
    def option_setup(func):
        optionParser = OptionParser(usage=usage)
        optionParser.disable_interspersed_args()
        for opt in option_list:
            optionParser.add_option(opt)
        optionParser.set_usage("%s [options] %s" % (func.__name__[3:], arg_desc))
        optionParser._func = func
        def new_func(instance, arg):
            try:
                opts, newArgList = optionParser.parse_args(arg.split())
                # Must find the remaining args in the original argument list, but
                # mustn't include the command itself
                #if hasattr(arg, 'parsed') and newArgList[0] == arg.parsed.command:
                #    newArgList = newArgList[1:]
                newArgs = remaining_args(arg, newArgList)
                if isinstance(arg, ParsedString):
                    arg = arg.with_args_replaced(newArgs)
                else:
                    arg = newArgs
            except optparse.OptParseError as e:
                print (e)
                optionParser.print_help()
                return
            if hasattr(opts, '_exit'):
                return None
            result = func(instance, arg, opts)
            return result
        if func.__doc__ is None and usage is None:
            func.__doc__ = ""
        elif func.__doc__ is None and usage:
            func.__doc__ = usage
        elif usage:
            func.__doc__ = '%s\n%s' % (usage, func.__doc__, )
        new_func.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help())
        return new_func
    return option_setup 
Example #26
Source File: tree.py    From pyang with ISC License 4 votes vote down vote up
def add_opts(self, optparser):
        optlist = [
            optparse.make_option("--tree-help",
                                 dest="tree_help",
                                 action="store_true",
                                 help="Print help on tree symbols and exit"),
            optparse.make_option("--tree-depth",
                                 type="int",
                                 dest="tree_depth",
                                 help="Number of levels to print"),
            optparse.make_option("--tree-line-length",
                                 type="int",
                                 dest="tree_line_length",
                                 help="Maximum line length"),
            optparse.make_option("--tree-path",
                                 dest="tree_path",
                                 help="Subtree to print"),
            optparse.make_option("--tree-print-groupings",
                                 dest="tree_print_groupings",
                                 action="store_true",
                                 help="Print groupings"),
            optparse.make_option("--tree-no-expand-uses",
                                 dest="tree_no_expand_uses",
                                 action="store_true",
                                 help="Do not expand uses of groupings"),
            optparse.make_option("--tree-module-name-prefix",
                                 dest="modname_prefix",
                                 action="store_true",
                                 help="Prefix with module names instead of " +
                                 "prefixes"),
            ]
        if plugin.is_plugin_registered('restconf'):
            optlist.append(
                optparse.make_option("--tree-print-yang-data",
                                     dest="tree_print_yang_data",
                                     action="store_true",
                                     help="Print ietf-restconf:yang-data " +
                                     "structures")
            )
        if plugin.is_plugin_registered('structure'):
            optlist.append(
                optparse.make_option("--tree-print-structures",
                                     dest="tree_print_structures",
                                     action="store_true",
                                     help="Print ietf-yang-structure-ext" +
                                     ":strcuture")
            )
        g = optparser.add_option_group("Tree output specific options")
        g.add_options(optlist) 
Example #27
Source File: cmd2.py    From Beehive with GNU General Public License v3.0 4 votes vote down vote up
def options(option_list, arg_desc="arg"):
    '''Used as a decorator and passed a list of optparse-style options,
       alters a cmd2 method to populate its ``opts`` argument from its
       raw text argument.

       Example: transform
       def do_something(self, arg):

       into
       @options([make_option('-q', '--quick', action="store_true",
                 help="Makes things fast")],
                 "source dest")
       def do_something(self, arg, opts):
           if opts.quick:
               self.fast_button = True
       '''
    if not isinstance(option_list, list):
        option_list = [option_list]
    for opt in option_list:
        options_defined.append(pyparsing.Literal(opt.get_opt_string()))
    def option_setup(func):
        optionParser = OptionParser()
        for opt in option_list:
            optionParser.add_option(opt)
        optionParser.set_usage("%s [options] %s" % (func.__name__[3:], arg_desc))
        optionParser._func = func
        def new_func(instance, arg):
            try:
                opts, newArgList = optionParser.parse_args(arg.split())
                # Must find the remaining args in the original argument list, but
                # mustn't include the command itself
                #if hasattr(arg, 'parsed') and newArgList[0] == arg.parsed.command:
                #    newArgList = newArgList[1:]
                newArgs = remaining_args(arg, newArgList)
                if isinstance(arg, ParsedString):
                    arg = arg.with_args_replaced(newArgs)
                else:
                    arg = newArgs
            except optparse.OptParseError as e:
                print (e)
                optionParser.print_help()
                return
            if hasattr(opts, '_exit'):
                return None
            result = func(instance, arg, opts)
            return result
        new_func.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help())
        return new_func
    return option_setup 
Example #28
Source File: git_p4.py    From python-zulip-api with Apache License 2.0 4 votes vote down vote up
def __init__(self):
        Command.__init__(self)
        P4UserMap.__init__(self)
        self.options = [
                optparse.make_option("--branch", dest="branch"),
                optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
                optparse.make_option("--changesfile", dest="changesFile"),
                optparse.make_option("--silent", dest="silent", action="store_true"),
                optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
                optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
                optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
                                     help="Import into refs/heads/ , not refs/remotes"),
                optparse.make_option("--max-changes", dest="maxChanges"),
                optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
                                     help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
                optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
                                     help="Only sync files that are included in the Perforce Client Spec")
        ]
        self.description = """Imports from Perforce into a git repository.\n
    example:
    //depot/my/project/ -- to import the current head
    //depot/my/project/@all -- to import everything
    //depot/my/project/@1,6 -- to import only from revision 1 to 6

    (a ... is not needed in the path p4 specification, it's added implicitly)"""

        self.usage += " //depot/path[@revRange]"
        self.silent = False
        self.createdBranches = set()
        self.committedChanges = set()
        self.branch = ""
        self.detectBranches = False
        self.detectLabels = False
        self.importLabels = False
        self.changesFile = ""
        self.syncWithOrigin = True
        self.importIntoRemotes = True
        self.maxChanges = ""
        self.keepRepoPath = False
        self.depotPaths = None
        self.p4BranchesInGit = []
        self.cloneExclude = []
        self.useClientSpec = False
        self.useClientSpec_from_options = False
        self.clientSpecDirs = None
        self.tempBranches = []
        self.tempBranchLocation = "git-p4-tmp"

        if gitConfig("git-p4.syncFromOrigin") == "false":
            self.syncWithOrigin = False

    # Force a checkpoint in fast-import and wait for it to finish 
Example #29
Source File: cmd2.py    From PocHunter with MIT License 4 votes vote down vote up
def options(option_list, arg_desc="arg"):
    '''Used as a decorator and passed a list of optparse-style options,
       alters a cmd2 method to populate its ``opts`` argument from its
       raw text argument.

       Example: transform
       def do_something(self, arg):

       into
       @options([make_option('-q', '--quick', action="store_true",
                 help="Makes things fast")],
                 "source dest")
       def do_something(self, arg, opts):
           if opts.quick:
               self.fast_button = True
       '''
    if not isinstance(option_list, list):
        option_list = [option_list]
    for opt in option_list:
        options_defined.append(pyparsing.Literal(opt.get_opt_string()))
    def option_setup(func):
        optionParser = OptionParser()
        for opt in option_list:
            optionParser.add_option(opt)
        optionParser.set_usage("%s [options] %s" % (func.__name__[3:], arg_desc))
        optionParser._func = func
        def new_func(instance, arg):
            try:
                opts, newArgList = optionParser.parse_args(arg.split())
                # Must find the remaining args in the original argument list, but 
                # mustn't include the command itself
                #if hasattr(arg, 'parsed') and newArgList[0] == arg.parsed.command:
                #    newArgList = newArgList[1:]
                newArgs = remaining_args(arg, newArgList)
                if isinstance(arg, ParsedString):
                    arg = arg.with_args_replaced(newArgs)
                else:
                    arg = newArgs
            except optparse.OptParseError as e:
                print (e)
                optionParser.print_help()
                return
            if hasattr(opts, '_exit'):
                return None
            result = func(instance, arg, opts)                            
            return result        
        new_func.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help())
        return new_func
    return option_setup 
Example #30
Source File: cmd2.py    From ZEROScan with MIT License 4 votes vote down vote up
def options(option_list, arg_desc="arg"):
    '''Used as a decorator and passed a list of optparse-style options,
       alters a cmd2 method to populate its ``opts`` argument from its
       raw text argument.

       Example: transform
       def do_something(self, arg):

       into
       @options([make_option('-q', '--quick', action="store_true",
                 help="Makes things fast")],
                 "source dest")
       def do_something(self, arg, opts):
           if opts.quick:
               self.fast_button = True
       '''
    if not isinstance(option_list, list):
        option_list = [option_list]
    for opt in option_list:
        options_defined.append(pyparsing.Literal(opt.get_opt_string()))
    def option_setup(func):
        optionParser = OptionParser()
        for opt in option_list:
            optionParser.add_option(opt)
        optionParser.set_usage("%s [options] %s" % (func.__name__[3:], arg_desc))
        optionParser._func = func
        def new_func(instance, arg):
            try:
                opts, newArgList = optionParser.parse_args(arg.split())
                # Must find the remaining args in the original argument list, but 
                # mustn't include the command itself
                #if hasattr(arg, 'parsed') and newArgList[0] == arg.parsed.command:
                #    newArgList = newArgList[1:]
                newArgs = remaining_args(arg, newArgList)
                if isinstance(arg, ParsedString):
                    arg = arg.with_args_replaced(newArgs)
                else:
                    arg = newArgs
            except optparse.OptParseError as e:
                print (e)
                optionParser.print_help()
                return
            if hasattr(opts, '_exit'):
                return None
            result = func(instance, arg, opts)                            
            return result        
        new_func.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help())
        return new_func
    return option_setup