Python argcomplete.autocomplete() Examples

The following are 30 code examples of argcomplete.autocomplete(). 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 argcomplete , or try the search function .
Example #1
Source File: shell_utils.py    From MDT with GNU Lesser General Public License v3.0 7 votes vote down vote up
def start(self, run_args=None):
        """ Starts a command and registers single handlers.

        Args:
            run_args (:class:`list`): the list of run arguments. If None we use sys.argv[1:].
        """
        if run_args is None:
            run_args = sys.argv[1:]

        parser = self._get_arg_parser()
        argcomplete.autocomplete(parser)

        if self.parse_unknown_args:
            args, unknown = parser.parse_known_args(run_args)
            self.run(args, unknown)
        else:
            args = parser.parse_args(run_args)
            self.run(args, {}) 
Example #2
Source File: main.py    From git-aggregator with GNU Affero General Public License v3.0 6 votes vote down vote up
def main():
    """Main CLI application."""

    parser = get_parser()

    argcomplete.autocomplete(parser, always_complete_options=False)

    args = parser.parse_args()
    if not args.command:
        args.command = "aggregate"

    setup_logger(
        level=args.log_level
    )

    try:
        run(args)
    except KeyboardInterrupt:
        pass 
Example #3
Source File: console.py    From python-sdk with MIT License 6 votes vote down vote up
def parse_commands(argv):
    """
    parse the input command
    """
    # 首先创建一个ArgumentParser对象
    parser = argparse.ArgumentParser(description="FISCO BCOS 2.0 lite client @python")
    parsed_args = argparse.Namespace()
    cmd = parser.add_argument("cmd", nargs="+", help="the command for console")  # 添加参数
    cmd.completer = completion

    argcomplete.autocomplete(parser)
    args = parser.parse_args()

    print("\nINFO >> user input : {}\n".format(args.cmd))
    cmd = args.cmd[0]
    inputparams = args.cmd[1:]
    return cmd, inputparams 
Example #4
Source File: terminal.py    From compoundpi with GNU General Public License v2.0 6 votes vote down vote up
def __call__(self, args=None):
        if args is None:
            args = sys.argv[1:]
        if argcomplete:
            argcomplete.autocomplete(self.parser, exclude=['-P'])
        elif 'COMP_LINE' in os.environ:
            return 0
        sys.excepthook = self.handle
        args = self.read_configuration(args)
        args = self.parser.parse_args(args)
        self.configure_logging(args)
        if args.debug:
            try:
                import pudb
            except ImportError:
                pudb = None
                import pdb
            return (pudb or pdb).runcall(self.main, args)
        else:
            return self.main(args) or 0 
Example #5
Source File: command.py    From crash with Apache License 2.0 6 votes vote down vote up
def _create_shell(crate_hosts, error_trace, output_writer, is_tty, args,
                  timeout=None, password=None):
    return CrateShell(crate_hosts,
                      error_trace=error_trace,
                      output_writer=output_writer,
                      is_tty=is_tty,
                      autocomplete=args.autocomplete,
                      autocapitalize=args.autocapitalize,
                      verify_ssl=args.verify_ssl,
                      cert_file=args.cert_file,
                      key_file=args.key_file,
                      ca_cert_file=args.ca_cert_file,
                      username=args.username,
                      password=password,
                      schema=args.schema,
                      timeout=timeout) 
Example #6
Source File: __init__.py    From snet-cli with MIT License 6 votes vote down vote up
def main():
    try:
        argv = sys.argv[1:]
        conf   = Config()
        parser = arguments.get_root_parser(conf)
        argcomplete.autocomplete(parser)

        try:
            args = parser.parse_args(argv)
        except TypeError:
            args = parser.parse_args(argv + ["-h"])

        getattr(args.cmd(conf, args), args.fn)()
    except Exception as e:
        if (sys.argv[1] == "--print-traceback"):
            raise
        else:
            print("Error:", e)
            print("If you want to see full Traceback then run:")
            print("snet --print-traceback [parameters]")
            sys.exit(42) 
Example #7
Source File: parse_cmake_help.py    From cmake_format with GNU General Public License v3.0 6 votes vote down vote up
def main():
  parser = argparse.ArgumentParser(description=__doc__)
  setup_argparse(parser)
  try:
    import argcomplete
    argcomplete.autocomplete(parser)
  except ImportError:
    pass
  args = parser.parse_args()

  thisdir = os.path.abspath(os.path.dirname(__file__))
  jenv = jinja2.Environment(
      loader=jinja2.FileSystemLoader(thisdir)
  )

  if args.command == "properties":
    get_properties(args, jenv)
  elif args.command == "variables":
    get_variables(args, jenv)
  elif args.command == "usages":
    cmd_get_usages(args, jenv)
  elif args.command == "deprecated":
    cmd_print_deprecated(args, jenv)
  else:
    logger.warning("Unknown command %s", args.command) 
Example #8
Source File: __init__.py    From matlab2cpp with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def m2cpp(args=None):
    """
    Execute main parser.

    Args:
        args (Optional[List[str]]):
            Argument to be parsed. If omitted, use ``sys.args``.
    """
    parser = create_parser()
    if argcomplete is not None:
        argcomplete.autocomplete(parser)

    args = parser.parse_args(args)

    from matlab2cpp.frontend import execute_parser
    execute_parser(args) 
Example #9
Source File: armory.py    From armory with GNU General Public License v3.0 6 votes vote down vote up
def list_report_options(module, module_name):

    config = get_config_options()
    db = initialize_database(config)
    # Load the module
    Module = load_module(module)
    if Module.Report.__doc__:
        print("%s" % module_name)

        print(Module.Report.__doc__)

    m = Module.Report(db)

    # Populate the options
    m.set_options()
    argcomplete.autocomplete(m.options)
    m.options.parse_args(["-h"]) 
Example #10
Source File: armory.py    From armory with GNU General Public License v3.0 6 votes vote down vote up
def list_module_options(module, module_name):

    config = get_config_options()
    db = initialize_database(config)
    # Load the module
    Module = load_module(module)
    if Module.Module.__doc__:
        print("%s" % module_name)

        print(Module.Module.__doc__)
    m = Module.Module(db)

    # Populate the options
    m.set_options()
    argcomplete.autocomplete(m.options)
    m.options.parse_args(["-h"]) 
Example #11
Source File: milc.py    From qmk_cli with MIT License 6 votes vote down vote up
def parse_args(self):
        """Parse the CLI args.
        """
        if self.args:
            self.log.debug('Warning: Arguments have already been parsed, ignoring duplicate attempt!')
            return

        argcomplete.autocomplete(self._arg_parser)

        self.acquire_lock()
        self.args = self._arg_parser.parse_args()

        if 'entrypoint' in self.args:
            self._entrypoint = self.args.entrypoint

        self.release_lock() 
Example #12
Source File: cli_parser.py    From trinity with MIT License 5 votes vote down vote up
def parse_cli_args() -> argparse.ArgumentParser:
    parser.set_defaults(func=_main)

    import_key_parser = subparser.add_parser("import-key", help=IMPORT_PARSER_HELP_MSG)
    import_key_parser.add_argument(
        "private_key", type=str, help=IMPORT_PARSER_KEY_ARGUMENT_HELP_MSG
    )
    import_key_parser.set_defaults(func=_import_key)

    argcomplete.autocomplete(parser)
    return parser 
Example #13
Source File: commands.py    From quantrocket-client with Apache License 2.0 5 votes vote down vote up
def main():
    parser = get_parser()
    if sys.stdin.isatty():
        try:
            import argcomplete
        except ImportError:
            pass
        else:
            argcomplete.autocomplete(parser)
    args = parser.parse_args()
    args = vars(args)
    args.pop("command")
    args.pop("subcommand", None)
    func_name = args.pop("func")
    func = import_func(func_name)
    try:
        result, exit_code = func(**args)
    except:
        if not sys.stdin.isatty():
            import traceback
            msg = traceback.format_exc()
            handle_error(msg)
        raise
    else:
        if result:
            # nonzero exit codes for non-interactive commands should be
            # logged
            if exit_code > 0 and not sys.stdin.isatty() and not sys.stdout.isatty():
                handle_error(result)
                print(result)
            # otherwise print
            else:
                print(result)

        return exit_code 
Example #14
Source File: abkhazia_main.py    From abkhazia with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        # at first, we load optional config file (--config
        # option). Values read from configuration are displayed as
        # default values in --help messages
        argv = self.load_config()

        # init the parser and subparsers for abkhazia
        parser = self.init_parser()

        # enable autocompletion and parse arguments
        argcomplete.autocomplete(parser)
        args = parser.parse_args(argv)

        # call the run() method of the parsed subcommand
        args.command(args) 
Example #15
Source File: completion.py    From knack with MIT License 5 votes vote down vote up
def enable_autocomplete(self, parser):
        if self.cli_ctx.data['completer_active']:
            argcomplete.autocomplete = argcomplete.CompletionFinder()
            argcomplete.autocomplete(parser, validator=lambda c, p: c.lower().startswith(p.lower()),
                                     default_completer=lambda _: ()) 
Example #16
Source File: entry_points.py    From evo with GNU General Public License v3.0 5 votes vote down vote up
def ape():
    from evo import main_ape
    parser = main_ape.parser()
    argcomplete.autocomplete(parser)
    launch(main_ape, parser) 
Example #17
Source File: entry_points.py    From evo with GNU General Public License v3.0 5 votes vote down vote up
def rpe():
    from evo import main_rpe
    parser = main_rpe.parser()
    argcomplete.autocomplete(parser)
    launch(main_rpe, parser) 
Example #18
Source File: entry_points.py    From evo with GNU General Public License v3.0 5 votes vote down vote up
def res():
    from evo import main_res
    parser = main_res.parser()
    argcomplete.autocomplete(parser)
    launch(main_res, parser) 
Example #19
Source File: entry_points.py    From evo with GNU General Public License v3.0 5 votes vote down vote up
def traj():
    from evo import main_traj
    parser = main_traj.parser()
    argcomplete.autocomplete(parser)
    launch(main_traj, parser) 
Example #20
Source File: conf.py    From rpg with GNU General Public License v2.0 5 votes vote down vote up
def parse_cmdline(self):
        self.parser = argparse.ArgumentParser(
            description="RPG is tool, that guides people through the " +
                        "creation of a RPM package. "
                        "RPG makes packaging much easier due to the " +
                        "automatic analysis of packaged files. "
                        "Beginners can get familiar with packaging process " +
                        "or the advanced users can use our tool " +
                        "for a quick creation of a package.",
            prog='rpg')
        self.parser.add_argument(
            '--plugin-dir', type=str, dest='plug_dir',
            help='Include plugin directory',
            metavar='<dir>', nargs='+')
        self.parser.add_argument(
            '--disable-plugin', type=str, dest='exc_plug',
            help='Exclude specific plugin', default=[],
            metavar='<plugin-name>', nargs='+')
        self.parser.add_argument(
            '--disable-dnf', dest='load_dnf', action='store_false',
            default=True, help='Disable loading DNF sack')
        try:
            import argcomplete
            argcomplete.autocomplete(self.parser)
        except ImportError:
            pass
        args = self.parser.parse_args()
        self.load_dnf = args.load_dnf
        if args.plug_dir:
            for arg in args.plug_dir:
                if path.isdir(arg):
                    self.directories.append(arg)
                else:
                    logging.warn('"' + arg + '" in not dir!')
        self.exclude = args.exc_plug 
Example #21
Source File: bootstrap.py    From trinity with MIT License 5 votes vote down vote up
def parse_and_validate_cli() -> argparse.Namespace:
    argcomplete.autocomplete(parser)

    args = parser.parse_args()

    if not args.genesis and args.network_id not in PRECONFIGURED_NETWORKS:
        parser.error(
            f"Unsupported network id: {args.network_id}. To use a network besides "
            "mainnet, ropsten or goerli, you must supply a genesis file with a flag, like "
            "`--genesis path/to/genesis.json`, also you must specify a data "
            "directory with `--data-dir path/to/data/directory`"
        )

    return args 
Example #22
Source File: entry_points.py    From evo_slam with GNU General Public License v3.0 5 votes vote down vote up
def traj():
    from evo import main_traj
    parser = main_traj.parser()
    argcomplete.autocomplete(parser)
    launch(main_traj, parser) 
Example #23
Source File: __init__.py    From python-libmaas with GNU Affero General Public License v3.0 5 votes vote down vote up
def main(argv=sys.argv):
    program, *arguments = argv
    program = program_name_from_env(program)
    parser, options = None, None

    try:
        parser = prepare_parser(program)
        argcomplete.autocomplete(parser, exclude=("-h", "--help"))
        options = parser.parse_args(arguments)
        try:
            execute = options.execute
        except AttributeError:
            parser.error("Argument missing.")
        else:
            return execute(options)
    except KeyboardInterrupt:
        raise SystemExit(1)
    except Exception as error:
        # This is unexpected. Why? Because the CLI code raises SystemExit or
        # invokes something that raises SystemExit when it chooses to exit.
        # SystemExit does not subclass Exception, and so it would not be
        # handled here, hence this is not a deliberate exit.
        if parser is None or options is None or options.debug:
            # The user has either chosen to debug OR we crashed before/while
            # parsing arguments. Either way, let's not be terse.
            if sys.stdin.isatty() and sys.stdout.isatty():
                # We're at a fully interactive terminal so let's post-mortem.
                *_, exc_traceback = sys.exc_info()
                post_mortem(exc_traceback)
                # Exit non-zero, but quietly; dumping the traceback again on
                # the way out is confusing after doing a post-mortem.
                raise SystemExit(1)
            else:
                # Re-raise so the traceback is dumped and we exit non-zero.
                raise
        else:
            # Display a terse error message. Note that parser.error() will
            # raise SystemExit(>0) after printing its message.
            parser.error("%s" % error) 
Example #24
Source File: main.py    From infrared with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    CoreServices.setup()

    # inject ansible config file
    CoreServices.ansible_config_manager().inject_config()

    specs_manager = api.SpecManager()

    # Init Managers
    specs_manager.register_spec(
        WorkspaceManagerSpec('workspace',
                             description="Workspace manager. "
                                         "Allows to create and use an "
                                         "isolated environment for plugins "
                                         "execution."))
    specs_manager.register_spec(
        PluginManagerSpec('plugin',
                          description="Plugin management"))

    specs_manager.register_spec(
        SSHSpec(
            'ssh',
            description="Interactive ssh session to node from inventory."))

    # register all plugins
    for plugin in CoreServices.plugins_manager().PLUGINS_DICT.values():
        specs_manager.register_spec(api.InfraredPluginsSpec(plugin))

    argcomplete.autocomplete(specs_manager.parser)
    return specs_manager.run_specs(args) or 0 
Example #25
Source File: export_sparse_subrepo.py    From cmake_format with GNU General Public License v3.0 5 votes vote down vote up
def main():
  logging.basicConfig(level=logging.INFO)
  argparser = argparse.ArgumentParser(description=__doc__)
  setup_argparser(argparser)
  try:
    import argcomplete
    argcomplete.autocomplete(argparser)
  except ImportError:
    pass
  args = argparser.parse_args()
  argdict = get_argdict(args)
  log_level = argdict.pop("log_level")
  logging.getLogger().setLevel(getattr(logging, log_level.upper()))
  return inner_main(**argdict) 
Example #26
Source File: clean_stage.py    From cmake_format with GNU General Public License v3.0 5 votes vote down vote up
def main():
  logging.basicConfig(level=logging.INFO)
  argparser = argparse.ArgumentParser(description=__doc__)
  setup_argparser(argparser)
  try:
    import argcomplete
    argcomplete.autocomplete(argparser)
  except ImportError:
    pass
  args = argparser.parse_args()
  inner_main(**get_argdict(args))
  return 0 
Example #27
Source File: github.py    From cmake_format with GNU General Public License v3.0 5 votes vote down vote up
def main():
  logging.basicConfig(level=logging.INFO)
  argparser = argparse.ArgumentParser(description=__doc__)
  setup_argparser(argparser)

  try:
    import argcomplete
    argcomplete.autocomplete(argparser)
  except ImportError:
    pass

  args = argparser.parse_args()
  argdict = get_argdict(args)
  command = argdict.pop("command")

  if command == "create-pseudorelease-tag":
    create_pseudorelease_tag(args.reposlug, args.branch)
  elif command == "sync-doc-artifacts":
    tag = argdict.pop("tag")
    if tag.startswith("pseudo-"):
      argdict["branch"] = tag[len("pseudo-"):]
    sync_doc_artifacts(**argdict)
  elif command == "push-release":
    push_release(args.reposlug, args.tag, args.message, args.files)
  else:
    logger.error("Unknown command %s", command)
    sys.exit(1) 
Example #28
Source File: __main__.py    From odoo-module-migrator with GNU Affero General Public License v3.0 5 votes vote down vote up
def main(args=False):
    # Parse Arguments
    parser = get_parser()
    argcomplete.autocomplete(parser, always_complete_options=False)
    if args:
        args = parser.parse_args(args)
    else:
        args = parser.parse_args()

    # Set log level
    setup_logger(args.log_level, args.log_path)

    try:
        # Create a new Migration Object
        module_names = args.modules\
            and [x.strip() for x in args.modules.split(",") if x.strip()] or []

        migration = Migration(
            args.directory, args.init_version_name, args.target_version_name,
            module_names, args.format_patch, args.remote_name,
            not args.no_commit,
        )

        # run Migration
        migration.run()

    except KeyboardInterrupt:
        pass 
Example #29
Source File: entry_points.py    From evo_slam with GNU General Public License v3.0 5 votes vote down vote up
def ape():
    from evo import main_ape
    parser = main_ape.parser()
    argcomplete.autocomplete(parser)
    launch(main_ape, parser) 
Example #30
Source File: entry_points.py    From evo_slam with GNU General Public License v3.0 5 votes vote down vote up
def rpe():
    from evo import main_rpe
    parser = main_rpe.parser()
    argcomplete.autocomplete(parser)
    launch(main_rpe, parser)