def test_find_learning_rate_args(self):
        parser = argparse.ArgumentParser(description="Testing")
        subparsers = parser.add_subparsers(title='Commands', metavar='')
        FindLearningRate().add_subparser('find_lr', subparsers)

        for serialization_arg in ["-s", "--serialization-dir"]:
            raw_args = [
                "find_lr", "path/to/params", serialization_arg,
                "serialization_dir"
            ]

            args = parser.parse_args(raw_args)

            assert args.func == find_learning_rate_from_args
            assert args.param_path == "path/to/params"
            assert args.serialization_dir == "serialization_dir"

        # config is required
        with self.assertRaises(SystemExit) as cm:  # pylint: disable=invalid-name
            args = parser.parse_args(["find_lr", "-s", "serialization_dir"])
            assert cm.exception.code == 2  # argparse code for incorrect usage

        # serialization dir is required
        with self.assertRaises(SystemExit) as cm:  # pylint: disable=invalid-name
            args = parser.parse_args(["find_lr", "path/to/params"])
            assert cm.exception.code == 2  # argparse code for incorrect usage
示例#2
0
def main(prog: str = None,
         subcommand_overrides: Dict[str, Subcommand] = {}) -> None:
    """
    The :mod:`~allennlp.run` command only knows about the registered classes in the ``allennlp``
    codebase. In particular, once you start creating your own ``Model`` s and so forth, it won't
    work for them, unless you use the ``--include-package`` flag.
    """

    parser = ArgumentParserWithDefaults(description="Run AllenNLP",
                                        usage="%(prog)s",
                                        prog=prog)
    parser.add_argument("--version",
                        action="version",
                        version="%(prog)s " + __version__)

    subparsers = parser.add_subparsers(title="Commands", metavar="")

    subcommands = {
        # Default commands
        "configure": Configure(),
        "train": Train(),
        "evaluate": Evaluate(),
        "predict": Predict(),
        "make-vocab": MakeVocab(),
        "elmo": Elmo(),
        "fine-tune": FineTune(),
        "dry-run": DryRun(),
        "test-install": TestInstall(),
        "find-lr": FindLearningRate(),
        "print-results": PrintResults(),
        # Superseded by overrides
        **subcommand_overrides,
    }

    for name, subcommand in subcommands.items():
        subparser = subcommand.add_subparser(name, subparsers)
        # configure doesn't need include-package because it imports
        # whatever classes it needs.
        if name != "configure":
            subparser.add_argument(
                "--include-package",
                type=str,
                action="append",
                default=[],
                help="additional packages to include",
            )

    args = parser.parse_args()

    # If a subparser is triggered, it adds its work as `args.func`.
    # So if no such attribute has been added, no subparser was triggered,
    # so give the user some help.
    if "func" in dir(args):
        # Import any additional modules needed (to register custom classes).
        for package_name in getattr(args, "include_package", ()):
            import_submodules(package_name)
        args.func(args)
    else:
        parser.print_help()
示例#3
0
def create_parser(
    prog: str = None,
    subcommand_overrides: Dict[str,
                               Subcommand] = None) -> argparse.ArgumentParser:
    """
    Creates the argument parser for the main program.
    """
    if subcommand_overrides is None:
        subcommand_overrides = {}

    parser = ArgumentParserWithDefaults(description="Run AllenNLP",
                                        usage="%(prog)s",
                                        prog=prog)
    parser.add_argument("--version",
                        action="version",
                        version="%(prog)s " + __version__)

    subparsers = parser.add_subparsers(title="Commands", metavar="")

    subcommands = {
        # Default commands
        "train": Train(),
        "evaluate": Evaluate(),
        "predict": Predict(),
        "elmo": Elmo(),
        "fine-tune": FineTune(),
        "dry-run": DryRun(),
        "make-vocab":
        DryRun(),  # deprecated, but keeping for backward compatibility.
        "test-install": TestInstall(),
        "find-lr": FindLearningRate(),
        "print-results": PrintResults(),
        # Superseded by overrides
        **subcommand_overrides,
    }

    for name, subcommand in subcommands.items():
        subparser = subcommand.add_subparser(name, subparsers)
        # configure doesn't need include-package because it imports
        # whatever classes it needs.
        if name != "configure":
            subparser.add_argument(
                "--include-package",
                type=str,
                action="append",
                default=[],
                help="additional packages to include",
            )

    return parser