Ejemplo n.º 1
0
 def add_arguments(self, parser: argparse.ArgumentParser) -> None:
     parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter
     parser.add_argument(
         "--output-json-file",
         default="Onespot-Sapir.json",
         help="Write the dictionary as JSON to this file",
     )
     parser.add_argument(
         "--input-tsv-file",
         default=DICTIONARY_PATH,
         help="Where to read the dictionary from",
     )
     group = parser.add_mutually_exclusive_group()
     group.add_argument(
         "--purge",
         action="store_true",
         help=(
             "Deletes ALL of the existing content imported to the database; "
             "do this only if you know what you're doing!"),
     )
     group.add_argument(
         "--json-only",
         action="store_true",
         help="Don’t write to the database",
     )
Ejemplo n.º 2
0
 def add_arguments(self, parser: ArgumentParser):
     parser.formatter_class = RawDescriptionHelpFormatter
     parser.add_argument("--csv-file", default=DEFAULT_SAMPLE_FILE)
     parser.add_argument(
         "--branch-checkout-dir",
         default=Path("~/alt/sample-query-branches").expanduser(),
         help="A directory in which to store branch checkouts and databases",
     )
     parser.add_argument(
         "--altlab-repo-checkout-dir",
         default=Path("~/alt/git/altlab").expanduser(),
         help=
         "Path to checkout of git repo containing full crkeng.xml; clone it from altlab.dev:/data/altlab.git",
     )
     parser.add_argument(
         "--re-run",
         action=BooleanOptionalAction,
         default=False,
         help=
         "re-run even if sample file, with sample.csv hash in name, already exists",
     )
     parser.add_argument(
         "--branch",
         action="append",
         default=[],
         help=f"Which branch(es) to run against, default={DEFAULT_BRANCHES}",
     )
Ejemplo n.º 3
0
def config_web_parser(parser: argparse.ArgumentParser, is_primary=False):
    """Configure the argument parser for the web command

    Args:
        parser: The parser to configure
        is_primary: True if configuring as the main command.  False if
            configuring as a sub-command.
    """
    parser.description = parawrap.fill(
        'Run builtin dev server or print a command that would run the server '
        'if the command were evaluated.  Although the production server will '
        'not be run directly, it could be run with:\n'
        '\n'
        '\t\'eval $({}{} web [OPTIONS] <production-server>)\''
        ''.format(cfg.PKG_NAME, '' if is_primary else ' web')
    )
    parser.formatter_class = MixedHelpFormatter
    parser.add_argument('--debug', '-d',
                        action='store_true',
                        help='Run the dev server with debug web iface and '
                             'reload server on source file changes')
    parser.add_argument('--host',
                        default=cfg.WEB_HOST,
                        help='Server host/name')
    parser.add_argument('--port', '-p',
                        type=int, default=cfg.WEB_PORT,
                        help='Port on which the server listens')
    parser.add_argument('server',
                        choices=('builtin', 'eventlet', 'gunicorn'), default='builtin',
                        help='Run builtin dev server or print command '
                             'related to running a specific production server')
    parser.set_defaults(func=web_cmd)
Ejemplo n.º 4
0
    def add_arguments(self, parser: ArgumentParser):
        parser.formatter_class = ArgumentDefaultsHelpFormatter

        parser.add_argument(
            "--crkeng-cleanup",
            action=BooleanOptionalAction,
            default=False,
            help="""
                Delete certain keys that are present but unused in the original
                crkeng importjson file.
            """,
        )
        parser.add_argument(
            "--output-file",
            help="Write output to this file, instead of overwriting the input",
        )

        group = parser.add_mutually_exclusive_group()
        group.add_argument(
            "--git-files",
            action="store_true",
            help="Sort all importjson files known to git",
        )
        group.add_argument(
            "json_files",
            help=f"The importjson file(s) to import",
            nargs="*",
            default=[DEFAULT_IMPORTJSON_FILE],
        )
def create_argument_parser():
    parser = ArgumentParser(description=__doc__)
    parser.formatter_class = ArgumentDefaultsHelpFormatter

    subparsers = parser.add_subparsers()

    def add_subparser(name, command):
        subparser = subparsers.add_parser(name, help=command.__doc__)
        subparser.set_defaults(func=command)
        return subparser

    def add_container_arg(subparser, allow_all=False):
        choices = [app.name for app in APPS]
        if allow_all:
            choices += ["all"]

        subparser.add_argument("container", choices=choices)
        return subparser

    add_subparser("make-yaml", make_yaml)
    add_subparser("setup", do_setup)

    add_container_arg(add_subparser("shell", shell))

    manage_subparser = add_container_arg(add_subparser("manage", manage),
                                         allow_all=True)
    manage_subparser.add_argument("manage_args", nargs=argparse.REMAINDER)

    staging_subparser = add_subparser("staging", staging)
    staging_subparser.add_argument("compose_args", nargs=argparse.REMAINDER)

    return parser
Ejemplo n.º 6
0
def add_environments(
        parser: argparse.ArgumentParser,
        completer: CompositeActionCompletionFinder,
        controller_mode: ControllerMode,
        target_mode: TargetMode,
) -> None:
    """Add arguments for the environments used to run ansible-test and commands it invokes."""
    no_environment = controller_mode == ControllerMode.NO_DELEGATION and target_mode == TargetMode.NO_TARGETS

    parser.set_defaults(no_environment=no_environment)

    if no_environment:
        return

    parser.set_defaults(target_mode=target_mode)

    add_global_options(parser, controller_mode)
    add_legacy_environment_options(parser, controller_mode, target_mode)
    action_types = add_composite_environment_options(parser, completer, controller_mode, target_mode)

    sections = [f'{heading}\n{content}'
                for action_type, documentation_state in CompositeAction.documentation_state.items() if action_type in action_types
                for heading, content in documentation_state.sections.items()]

    if not get_ci_provider().supports_core_ci_auth():
        sections.append('Remote provisioning options have been hidden since no Ansible Core CI API key was found.')

    sections.append(get_epilog(completer))

    parser.formatter_class = argparse.RawDescriptionHelpFormatter
    parser.epilog = '\n\n'.join(sections)
Ejemplo n.º 7
0
    def get_parser(self):
        p = ArgumentParser(self.description)
        p.formatter_class = argparse.RawDescriptionHelpFormatter
        p.add_argument('-a', '--all', action='store_true', default=False,
                       help="Display all images")
        p.add_argument('-l', '--long', action='store_true', default=False,
                       help='Display extra information for each image')
        p.add_argument('--sharedwith', action='store_true', default=False,
                       help='modifier flag.  See epilog for examples.')
        g = p.add_mutually_exclusive_group()
        g.add_argument('-u', '--user', help='List images owned by USER')
        g.add_argument('-g', '--group', help="List images shared with GROUP.")
        p.epilog = """\
Example Usages:

    repoman list
        list the current users images

    repoman list --sharedwith
        list all images shared with the current user

    repoman list --user bob
        list all images owned by the user 'bob'

    repoman list --sharedwith --user bob
        list all images shared with the user 'bob'

    repoman list --group babar
        list all images accessible by members of the 'babar' group

    repoman list --sharedwith --group babar
        has the same effect as the previous example."""

        return p
    def add_arguments(self, parser: ArgumentParser):
        parser.formatter_class = ArgumentDefaultsHelpFormatter

        parser.add_argument(
            "--purge",
            action=BooleanOptionalAction,
            default=False,
            help="""
                Delete all existing entries that are not found in this import
                file. Used for importing a full dictionary file when keys may
                have changed.
            """,
        )
        parser.add_argument(
            "--atomic",
            action=BooleanOptionalAction,
            default=settings.DEBUG,
            help="""
                Run the import in a single transaction. This will make the
                import run much faster, but will lock up the database so that
                other processes can’t access it. Good for development use.
            """,
        )
        parser.add_argument(
            "--translate-wordforms",
            action=BooleanOptionalAction,
            default=settings.MORPHODICT_SUPPORTS_AUTO_DEFINITIONS,
            help="""
                Whether to attempt to provide automatic translations for
                inflected forms
            """,
        )
        parser.add_argument(
            "--incremental",
            action=BooleanOptionalAction,
            default=False,
            help="""
                Skip import of lemmas and their related forms if the associated
                importjson content has not changed since they were last
                imported.

                You will not want to use this if the language FSTs, the paradigm
                tables, or the phrase translation FSTs have been updated since
                the last import.
            """,
        )
        parser.add_argument(
            "--skip-building-vectors-because-testing",
            default=False,
            help=argparse.SUPPRESS,
        )
        parser.add_argument(
            "json_file",
            help=f"The importjson file to import",
            nargs="?",
            default=DEFAULT_IMPORTJSON_FILE,
        )
Ejemplo n.º 9
0
def setup_common_cli_parser() -> ArgumentParser:
    parser = ArgumentParser()
    parser = Trainer.add_argparse_args(parser)
    parser.formatter_class = ArgumentDefaultsHelpFormatter
    parser.add_argument('--config-dir', type=Path, default=Path('conf'))
    parser.add_argument('--config-file-name', default='config.yaml')
    parser.add_argument('--print-final-config', action='store_true')
    parser.add_argument('overrides', nargs='*')
    return parser
Ejemplo n.º 10
0
    def sample_usage(self, parser: ArgumentParser, intent: str, commands: list):
        parser.formatter_class = argparse.RawDescriptionHelpFormatter
        if not self.sample_usage_text:
            self.epilog_text = parser.epilog
            self.sample_usage_text = "sample usages:\n\n"

        self.sample_usage_text += intent + "\n  "
        self.sample_usage_text += "\n  ".join(commands) + "\n\n"

        parser.epilog = self.sample_usage_text + self.epilog_text
Ejemplo n.º 11
0
def parse_arguments(parser: argparse.ArgumentParser, argv: Sequence[str]) -> Args:
    parser.formatter_class = argparse.RawTextHelpFormatter
    parser.add_argument("--debug",
                        "-d",
                        action="store_true",
                        help="Enable debug mode (keep some exceptions unhandled)")
    parser.add_argument("--connect-timeout",
                        type=int,
                        default=10,
                        help="Timeout in seconds for network connects (default=10)")

    parser.add_argument("--fetch-server",
                        type=str,
                        required=True,
                        metavar="ADDRESS",
                        help="Host address of the IMAP/POP3 server hosting your mailbox")
    parser.add_argument("--fetch-username",
                        type=str,
                        required=True,
                        metavar="USER",
                        help="Username to use for IMAP/POP3")
    parser.add_argument("--fetch-password",
                        type=str,
                        required=True,
                        metavar="PASSWORD",
                        help="Password to use for IMAP/POP3")
    parser.add_argument("--fetch-protocol",
                        type=str.upper,
                        choices={'IMAP', 'POP3'},
                        help="Set to 'IMAP' or 'POP3', depending on your mailserver "
                        "(default=IMAP)")
    parser.add_argument("--fetch-port",
                        type=int,
                        metavar="PORT",
                        help="IMAP or POP3 port (defaults to 110 for POP3 and 995 for POP3 "
                        "with TLS/SSL and 143 for IMAP and 993 for IMAP with TLS/SSL)")
    parser.add_argument("--fetch-tls",
                        "--fetch-ssl",
                        action="store_true",
                        help="Use TLS/SSL for feching the mailbox (disabled by default)")

    parser.add_argument("--verbose", '-v', action="count", default=0)

    try:
        args = parser.parse_args(argv)
    except SystemExit:
        # we have no efficient way to control the output on stderr but at least we can return
        # UNKNOWN
        raise SystemExit(3)

    args.fetch_port = args.fetch_port or (
        (995 if args.fetch_tls else 110) if args.fetch_protocol == 'POP3' else
        (993 if args.fetch_tls else 143))
    return args
Ejemplo n.º 12
0
    def sample_usage(self, parser: ArgumentParser, intent: str,
                     commands: list):
        parser.formatter_class = argparse.RawDescriptionHelpFormatter
        if not self.sample_usage_text:
            self.epilog_text = parser.epilog
            self.sample_usage_text = 'sample usages:\n\n'

        self.sample_usage_text += intent + '\n  '
        self.sample_usage_text += '\n  '.join(commands) + '\n\n'

        parser.epilog = self.sample_usage_text + self.epilog_text
Ejemplo n.º 13
0
 def _init_argparse(self, parser: argparse.ArgumentParser) -> None:
     parser.add_argument(
         '-H',
         action='store_false',
         help=
         'do not display headers and separate fields by a single tab (scripted mode)'
     )
     parser.add_argument('-o',
                         metavar="FIELDS",
                         help='comma-separated list of fields to display')
     parser.add_argument('-p',
                         action='store_true',
                         help='display numbers in parseable (exact) values')
     parser.add_argument(
         '-r',
         '--recursive',
         action='store_true',
         help='recurse down children caches and print statistics')
     parser.add_argument('-s', metavar="FIELD", help='sort rows by FIELD')
     parser.add_argument('-v',
                         action='store_true',
                         help='Print all statistics')
     #
     # We change the formatter so we can add newlines in the epilog.
     #
     parser.formatter_class = argparse.RawDescriptionHelpFormatter
     parser.epilog = textwrap.fill(
         f"FIELDS := {', '.join(SplKmemCaches.FIELDS.keys())}\n",
         width=80,
         replace_whitespace=False)
     parser.epilog += "\n\n"
     parser.epilog += textwrap.fill(
         ("If -o is not specified the default fields used are "
          f"{', '.join(SplKmemCaches.DEFAULT_FIELDS)}.\n"),
         width=80,
         replace_whitespace=False)
     parser.epilog += "\n\n"
     parser.epilog += textwrap.fill(
         ("If the -s option is not specified and the command's "
          "output is not piped anywhere then we sort by the "
          "following fields in order: "
          f"{', '.join(SplKmemCaches.DEFAULT_SORT_FIELDS)}. "
          "If none of those exists in the field-set we sort by "
          "the first field specified in the set."),
         width=80,
         replace_whitespace=False)
Ejemplo n.º 14
0
    def add_arguments(self, parser: ArgumentParser):
        parser.formatter_class = ArgumentDefaultsHelpFormatter

        parser.add_argument(
            "--full-importjson",
            help="The full dictionary file to read in",
            default=DEFAULT_FULL_IMPORTJSON_FILE,
        )
        parser.add_argument(
            "--test-importjson",
            help="The test dictionary file to write out",
            default=DEFAULT_TEST_IMPORTJSON_FILE,
        )
        parser.add_argument(
            "--test-db-words-file",
            help="The list of test words to use in the test dictionary",
            default=TEST_DB_TXT_FILE,
        )
Ejemplo n.º 15
0
    def get_parser(self):
        p = ArgumentParser(self.description)
        p.formatter_class = argparse.RawDescriptionHelpFormatter
        p.add_argument('-a',
                       '--all',
                       action='store_true',
                       default=False,
                       help="Display all images")
        p.add_argument('-l',
                       '--long',
                       action='store_true',
                       default=False,
                       help='Display extra information for each image')
        p.add_argument('--sharedwith',
                       action='store_true',
                       default=False,
                       help='modifier flag.  See epilog for examples.')
        g = p.add_mutually_exclusive_group()
        g.add_argument('-u', '--user', help='List images owned by USER')
        g.add_argument('-g', '--group', help="List images shared with GROUP.")
        p.epilog = """\
Example Usages:

    repoman list
        list the current users images

    repoman list --sharedwith
        list all images shared with the current user

    repoman list --user bob
        list all images owned by the user 'bob'

    repoman list --sharedwith --user bob
        list all images shared with the user 'bob'

    repoman list --group babar
        list all images accessible by members of the 'babar' group

    repoman list --sharedwith --group babar
        has the same effect as the previous example."""

        return p
Ejemplo n.º 16
0
    def add_arguments(self, parser: ArgumentParser):
        parser.formatter_class = ArgumentDefaultsHelpFormatter

        parser.add_argument(
            "--full-importjson",
            help="The full dictionary file to read in",
            default=DEFAULT_FULL_IMPORTJSON_FILE,
        )
        parser.add_argument(
            "--output-importjson",
            help="The test dictionary file to write out",
            default=DEFAULT_FULL_IMPORTJSON_FILE.with_stem(
                f"{morphodict_language_pair()}_subset_dictionary"),
        )
        parser.add_argument(
            "--percentage",
            type=float,
            help="What percent of words to keep",
            default=10,
        )
    def add_arguments(self, parser: ArgumentParser):
        """
        Set up command line arguments

        :param parser: The command line parser
        """
        parser.add_argument('-b', '--brokers', nargs='+', metavar='HOST:PORT', default=['localhost:9092'],
                            help='The Kafka brokers to bootstrap from')
        parser.add_argument('-s', '--source-address',
                            help='Source address to use when connecting to Kafka')
        parser.add_argument('-t', '--topic', default='dhcpkit.messages',
                            help='The topic to subscribe to')
        parser.add_argument('-g', '--consumer-group', default='dhcpkit_looking_glass',
                            help='The consumer group we belong to, for progress tracking')
        parser.add_argument('--from-beginning', action='store_true',
                            help='Start processing messages from the beginning instead of continuing')
        parser.add_argument('--skip-backlog', action='store_true',
                            help='Ignore old messages instead of continuing where we left off')

        parser.formatter_class = ArgumentDefaultsHelpFormatter
Ejemplo n.º 18
0
    log("Done saving")
    return paramb




""" parse console arguments """
print("[PyRE] - Version 1.0\n")

help_message = "What params shall i parse today?\n\n" \
                + "Default settings if not otherwise specified:\n"     \
                + f"Path to Param Directory:  {param_path_default}\n"   \
                + f"Path to Layout Directory: {layout_path_default}\n" \
                + f"Path to Output Directory: {save_dir_default}\n"
parser = ArgumentParser(description=help_message)
parser.formatter_class = RawDescriptionHelpFormatter
parser.add_argument("-n", "--name", "--param", dest="param_name", default="Bullet",
                    help="Name of the Param to use", metavar="name")
parser.add_argument("-p", "--path", dest="param_path", default=param_path_default,
                    help="Path to directory with param files (GameParam)", metavar="path")
parser.add_argument("-l", "--layout", dest="layout_path", default=layout_path_default,
                    help="Path to directory with xml Layout files", metavar="path")
parser.add_argument("-o", "--out", dest="out_path", default=save_dir_default,
                    help="Output Directory (file name is set automatically)", metavar="path")     
#Alternative
parser.add_argument("-fp", "--file", dest="param_filename", default="",
                    help="Param file to use (instead of path + name)", metavar="file")
parser.add_argument("-fl", "--file_layout", dest="layout_filename", default="",
                    help="Layout file to use (instead of path + name) NOT SUPPORTET YET", metavar="file")

Ejemplo n.º 19
0
 def _mk_usage(self, parser: ArgumentParser) -> literal_block:
     parser.formatter_class = lambda prog: HelpFormatter(prog, width=self.options.get("usage_width", 100))
     texts = parser.format_usage()[len("usage: ") :].splitlines()
     texts = [line if at == 0 else f"{' ' * (len(parser.prog) + 1)}{line.lstrip()}" for at, line in enumerate(texts)]
     return literal_block("", Text("\n".join(texts)))
Ejemplo n.º 20
0
def inject_args(
    parser: argparse.ArgumentParser,
    hp_mgr: hpman.HyperParameterManager,
    *,
    inject_actions: List[str],
    action_prefix: str,
    serial_format: str,
    show_defaults: bool,
) -> argparse.ArgumentParser:
    """Inject hpman parsed hyperparameter settings into argparse arguments.
    Only a limited set of format are supported. See code for details.

    :param parser: Use given parser object of `class`:`argparse.ArgumentParser`.
    :param hp_mgr: A `class`:`hpman.HyperParameterManager` object.

    :param inject_actions: A list of actions names to inject
    :param action_prefix: Prefix for hpargparse related options
    :param serial_format: One of 'yaml' and 'pickle'
    :param show_defaults: Show default values

    :return: The injected parser.
    """

    help = ""
    if show_defaults:
        parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter

        # Default value will be shown when using argparse.ArgumentDefaultsHelpFormatter
        # only if a help message is present. This is the behavior of argparse.
        help = " "

    # add options for collected hyper-parameters
    for k, v in hp_mgr.get_values().items():
        # this is just a simple hack
        option_name = "--{}".format(k.replace("_", "-"))

        if _get_argument_type_by_value(v) == bool:
            # argparse does not directly support bool types.
            parser.add_argument(
                option_name, type=str2bool, default=v, help=help  # EmptyValue(),
            )
        else:
            parser.add_argument(
                option_name,
                type=_get_argument_type_by_value(v),
                default=v,  # EmptyValue()
                help=help,
            )

    make_option = lambda name: "--{}-{}".format(action_prefix, name)

    for action in inject_actions:
        if action == "list":
            parser.add_argument(
                make_option("list"),
                action="store",
                default=False,
                const="yaml",
                nargs="?",
                choices=["detail", "yaml"],
                help=(
                    "List all available hyperparameters. If `{} detail` is"
                    " specified, a verbose table will be print"
                ).format(make_option("list")),
            )
        elif action == "save":
            parser.add_argument(
                make_option("save"),
                help=(
                    "Save hyperparameters to a file. The hyperparameters"
                    " are saved after processing of all other options"
                ),
            )

        elif action == "load":
            parser.add_argument(
                make_option("load"),
                help=(
                    "Load hyperparameters from a file. The hyperparameters"
                    " are loaded before any other options are processed"
                ),
            )

    if "load" in inject_actions or "save" in inject_actions:
        parser.add_argument(
            make_option("serial-format"),
            default=serial_format,
            choices=config.HP_SERIAL_FORMAT_CHOICES,
            help=(
                "Format of the saved config file. Defaults to {}."
                " It can be set to override auto file type deduction."
            ).format(serial_format),
        )

    if inject_actions:
        parser.add_argument(
            make_option("exit"),
            action="store_true",
            help="process all hpargparse actions and quit",
        )

    return parser
Ejemplo n.º 21
0
def main(argv=None, testing=False):  # pylint: disable=locally-disabled, too-many-locals, R0915, too-many-branches
    '''Command line options.'''

    if argv is None:
        argv = sys.argv
    elif not testing:
        sys.argv.extend(argv)
    else:
        sys.argv = argv
    program_version = "%s" % __version__
    program_build_date = str(__updated__)
    program_version_message = '%%(prog)s %s (%s)' % (program_version,
                                                     program_build_date)
    program_shortdesc = __doc__.split("\n")[1]
    program_license = '''%s

  Created by Sarvi Shanmugham on %s.
  Copyright 2016 Cisco Inc. All rights reserved.

USAGE
''' % (program_shortdesc, str(__date__))
    program_epilog = '''
wisktrack - track depencencies

Example:
    wisktrack
'''

    init = False
    try:
        init = clientenv.env_init(env.gettoolname(__programname__,
                                                  subcommands=0),
                                  env.CLIENT_CFG_SEARCH,
                                  doclientcfg=True)

        parser = ArgumentParser(description=program_license,
                                epilog=program_epilog,
                                formatter_class=RawDescriptionHelpFormatter)

        parser.epilog = program_epilog
        parser.formatter_class = RawDescriptionHelpFormatter
        parser.add_argument("-v",
                            "--verbose",
                            dest="verbose",
                            action="count",
                            default=0,
                            help="Set verbosity level [default: %(default)s]")
        parser.add_argument('-V',
                            '--version',
                            action='version',
                            version=program_version_message)
        parser.add_argument('-show',
                            '--show',
                            action='store_true',
                            default=False,
                            help="Show Depenency Data")
        parser.add_argument('-clean',
                            '--clean',
                            action='store_true',
                            default=False,
                            help="Show Cleaned Command Tree ")
        parser.add_argument('-trace',
                            '--trace',
                            action='store_true',
                            default=False,
                            help="Trace to file")
        parser.add_argument('-wsroot',
                            '--wsroot',
                            type=str,
                            default=os.getcwd(),
                            help="Workspace Root")
        parser.add_argument('-trackfile',
                            '--trackfile',
                            type=str,
                            default=os.path.join(os.getcwd(), WISK_DEPDATA),
                            help="Where to output the tracking data")
        parser.add_argument('-config',
                            '--config',
                            type=str,
                            default=WISK_PARSER_CFG,
                            help="WISK Parser Configration")
        parser.add_argument('-extract',
                            '--extract',
                            type=str,
                            default=[],
                            help="Extract specific nodes Parser Configration")
        parser.add_argument(
            '-environ',
            '--environ',
            type=str,
            action='append',
            default=['PATH', 'LOGNAME', 'LANGUAGE', 'HOME', 'USER', 'SHELL'],
            help='Environment variables for carry forward')
        parser.add_argument('-filter',
                            '--filter',
                            type=str,
                            default=None,
                            help='Filtered list of events to track')

        args = partialparse(parser)

        env.logging_setup(args.verbose)
        configparse(args.config)
        insight_init(args)

        return dotrack(args)
    except KeyboardInterrupt:
        # handle keyboard interrupt
        return 0
    except CmdException as ex:
        print(ex.message)
        print(
            "\nFor Assistance: please open a ticket at http://devxsupport.cisco.com/, BU:DevX Tools, OS:Common Tools(non-OS specific), Tool:WIT"
        )
        return 1
    except Exception as ex:  # pylint: disable=locally-disabled, broad-except
        logerror = log.error if init else print
        logwarn = log.warn if init else print
        logwarn(traceback.format_exc())
        if not args or not args.verbose:
            err_property = None
            if hasattr(ex, 'message'):
                err_property = getattr(ex, 'message', None)
            if (err_property is None or err_property == '') and hasattr(
                    ex, 'error'):
                err_property = getattr(ex, 'error', None)
            else:
                err_property = getattr(ex, '', None)
            logerror('Error %s' % html2text(str(err_property)))
        print('Commmand: %s' % __programpath__)
        print("  for help use --help")
        print(
            "\nFor Assistance: please open a ticket at http://devxsupport.cisco.com/, BU:DevX Tools, OS:Common Tools(non-OS specific), Tool:WIT"
        )
        return 2
Ejemplo n.º 22
0
def parse_arguments(parser: argparse.ArgumentParser,
                    argv: Sequence[str]) -> Args:
    parser.formatter_class = argparse.RawTextHelpFormatter
    parser.add_argument(
        "--debug",
        "-d",
        action="store_true",
        help="Enable debug mode (keep some exceptions unhandled)",
    )
    parser.add_argument(
        "--connect-timeout",
        type=int,
        default=10,
        help="Timeout in seconds for network connects (default=10)",
    )

    parser.add_argument(
        "--fetch-server",
        type=str,
        required=True,
        metavar="ADDRESS",
        help="Host address of the IMAP/POP3/EWS server hosting your mailbox",
    )
    parser.add_argument(
        "--fetch-username",
        type=str,
        required=True,
        metavar="USER",
        help="Username to use for IMAP/POP3/EWS",
    )
    parser.add_argument(
        "--fetch-password",
        type=str,
        required=True,
        metavar="PASSWORD",
        help="Password to use for IMAP/POP3/EWS",
    )
    parser.add_argument(
        "--fetch-protocol",
        type=str.upper,
        choices={"IMAP", "POP3", "EWS"},
        help=
        "Set to 'IMAP', 'POP3' or 'EWS', depending on your mailserver (default=IMAP)",
    )
    parser.add_argument(
        "--fetch-port",
        type=int,
        metavar="PORT",
        help="IMAP or POP3 port (defaults to 110/995 (TLS) for POP3"
        " 143/993 (TLS) for IMAP and 80/443 (TLS) otherwise)",
    )
    parser.add_argument(
        "--fetch-tls",
        "--fetch-ssl",
        action="store_true",
        help="Use TLS/SSL for feching the mailbox (disabled by default)",
    )
    parser.add_argument("--no-cert-check",
                        action="store_true",
                        help="Don't enforce SSL/TLS certificate validation")

    parser.add_argument("--verbose", "-v", action="count", default=0)

    try:
        args = parser.parse_args(argv)
    except SystemExit:
        # we have no efficient way to control the output on stderr but at least we can return
        # UNKNOWN
        raise SystemExit(3)

    args.fetch_port = args.fetch_port or (
        (995 if args.fetch_tls else 110) if args.fetch_protocol == "POP3" else
        (993 if args.fetch_tls else 143) if args.fetch_protocol == "IMAP" else
        (443 if args.fetch_tls else 80)  # HTTP / REST (e.g. EWS)
    )
    return args
Ejemplo n.º 23
0
def inject_args(
    parser: argparse.ArgumentParser,
    hp_mgr: hpman.HyperParameterManager,
    *,
    inject_actions: List[str],
    action_prefix: str,
    serial_format: str,
    show_defaults: bool,
) -> argparse.ArgumentParser:
    """Inject hpman parsed hyperparameter settings into argparse arguments.
    Only a limited set of format are supported. See code for details.

    :param parser: Use given parser object of `class`:`argparse.ArgumentParser`.
    :param hp_mgr: A `class`:`hpman.HyperParameterManager` object.

    :param inject_actions: A list of actions names to inject
    :param action_prefix: Prefix for hpargparse related options
    :param serial_format: One of 'yaml' and 'pickle'
    :param show_defaults: Show default values

    :return: The injected parser.
    """

    help = ""
    if show_defaults:
        parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter

        # Default value will be shown when using argparse.ArgumentDefaultsHelpFormatter
        # only if a help message is present. This is the behavior of argparse.
        help = " "

    value_names_been_set = set()

    def _make_value_names_been_set_injection(name, func):
        @functools.wraps(func)
        def wrapper(string):
            # when isinstance(default, string),
            # the `parser.parse_args()` will run type(default) automaticly.
            # value_names_been_set should ignore these names.
            if not isinstance(string, StringAsDefault):
                value_names_been_set.add(name)
            return func(string)

        return wrapper

    # add options for collected hyper-parameters
    for k, v in hp_mgr.get_values().items():
        # this is just a simple hack
        option_name = "--{}".format(k.replace("_", "-"))

        if _get_argument_type_by_value(v) == bool:
            # argparse does not directly support bool types.
            parser.add_argument(
                option_name,
                type=_make_value_names_been_set_injection(k, str2bool),
                default=v,
                help=help,
            )
        else:
            if isinstance(v, str):
                # if isinstance(v, str), mark as StringAsDefault
                v = StringAsDefault(v)
            parser.add_argument(
                option_name,
                type=_make_value_names_been_set_injection(
                    k, _get_argument_type_by_value(v)),
                default=v,
                help=help,
            )

    make_option = lambda name: "--{}-{}".format(action_prefix, name)

    for action in inject_actions:
        if action == "list":
            parser.add_argument(
                make_option("list"),
                action="store",
                default=None,
                const="yaml",
                nargs="?",
                choices=["detail", "yaml", "json"],
                help=("List all available hyperparameters. If `{} detail` is"
                      " specified, a verbose table will be print").format(
                          make_option("list")),
            )
        elif action == "detail":
            parser.add_argument(
                make_option("detail"),
                action="store_true",
                help="Shorthand for --hp-list detail",
            )
        elif action == "save":
            parser.add_argument(
                make_option("save"),
                help=("Save hyperparameters to a file. The hyperparameters"
                      " are saved after processing of all other options"),
            )

        elif action == "load":
            parser.add_argument(
                make_option("load"),
                help=("Load hyperparameters from a file. The hyperparameters"
                      " are loaded before any other options are processed"),
            )

    if "load" in inject_actions or "save" in inject_actions:
        parser.add_argument(
            make_option("serial-format"),
            default=serial_format,
            choices=config.HP_SERIAL_FORMAT_CHOICES,
            help=("Format of the saved config file. Defaults to {}."
                  " It can be set to override auto file type deduction."
                  ).format(serial_format),
        )

    if inject_actions:
        parser.add_argument(
            make_option("exit"),
            action="store_true",
            help="process all hpargparse actions and quit",
        )

    def __hpargparse_value_names_been_set(self):
        return value_names_been_set

    parser.__hpargparse_value_names_been_set = MethodType(
        __hpargparse_value_names_been_set, parser)

    return parser
Ejemplo n.º 24
0
    def add_arguments(self, parser: ArgumentParser) -> None:
        parser.add_argument('filepath', help="Path to credentials.json")

        parser.formatter_class = RawTextHelpFormatter
        parser.description = f'''Use the init command to initialise the token and to set up your gmail account for hassle-free mail deliveries.
Ejemplo n.º 25
0
def commandmaker():
    name = os.path.basename(sys.argv[0]).split('.')[0]
    desc = 'password generator for UNIX based systems\n' \
           'it uses the system entropy (/dev/urandom) for password generation'
    foot = 'Copyright (C) 2018-2020 _kodokami'

    parser = ArgumentParser(prog=name,
                            description=desc,
                            epilog=foot,
                            add_help=False)
    parser.formatter_class = RawTextHelpFormatter

    # password options
    pass_args = parser.add_argument_group(title='password options')

    pass_args.add_argument(
        '-t',
        '--password-type',
        action='store',
        metavar='TYPE',
        type=_pass_type,
        help='password type (def: standard), available options:\n'
        '  - num | numeric    - numeric password (PIN)\n'
        '  - low | lowercase  - alphanumeric password with lowercase characters only\n'
        '  - upp | uppercase  - alphanumeric password with uppercase characters only\n'
        '  - std | standard   - standard alphanumeric password with mixed characters',
        default='std',
        required=False)

    pass_args.add_argument('-l',
                           '--password-length',
                           action='store',
                           type=_positive_num,
                           help='password length (def: 12)',
                           default=12,
                           required=False,
                           metavar='LENGTH')

    pass_args.add_argument('-s',
                           '--special-characters',
                           action='store_true',
                           help='adds special characters to the pool',
                           dest='special')

    pass_args.add_argument(
        '-S',
        '--safe',
        action='store_true',
        help='removes confusing characters from pool (l, I, O, 0, etc.)')

    # script options
    script_args = parser.add_argument_group(title='other')

    script_args.add_argument(
        '-c',
        '--passwords-count',
        action='store',
        type=_positive_num,
        help='describes how many passwords should be generated (def: 3)',
        default=3,
        required=False,
        metavar='COUNT')

    script_args.add_argument('--compact',
                             action='store_true',
                             help='compact view with space as a separator')

    script_args.add_argument('-v',
                             '--version',
                             action='version',
                             version=f'{name} v{__version__}',
                             help='show program version and exit')

    script_args.add_argument('-h',
                             '--help',
                             action='help',
                             help='show this help message and exit')

    return parser.parse_args()