Python click.command() Examples

The following are 30 code examples of click.command(). 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 click , or try the search function .
Example #1
Source File: adapter.py    From django-click with MIT License 8 votes vote down vote up
def run_from_argv(self, argv):
        """
        Called when run from the command line.
        """
        prog_name = "{} {}".format(os.path.basename(argv[0]), argv[1])
        try:
            # We won't get an exception here in standalone_mode=False
            exit_code = self.main(
                args=argv[2:], prog_name=prog_name, standalone_mode=False
            )
            if exit_code:
                sys.exit(exit_code)
        except click.ClickException as e:
            if getattr(e.ctx, "traceback", False):  # NOCOV
                raise
            e.show()
            sys.exit(e.exit_code) 
Example #2
Source File: test_clickDescendents.py    From isitfit with Apache License 2.0 7 votes vote down vote up
def test_ClickOption_failsWithPrompt(runner):
  @click.group()
  def isitfit(): pass

  @click.group()
  @click.option('--prompt', default='foo', prompt='my prompt', type=str)
  def cost(prompt): pass

  @click.command()
  def analyze(): pass

  cost.add_command(analyze)
  isitfit.add_command(cost)

  # invoke and assert
  result = runner.invoke(isitfit, ['cost', '--help'])
  assert False # the invoke above is expected to halt at the prompt and fail, but not working as expected ATM 
Example #3
Source File: cli.py    From recruit with Apache License 2.0 6 votes vote down vote up
def main(as_module=False):
    args = sys.argv[1:]

    if as_module:
        this_module = 'flask'

        if sys.version_info < (2, 7):
            this_module += '.cli'

        name = 'python -m ' + this_module

        # Python rewrites "python -m flask" to the path to the file in argv.
        # Restore the original command so that the reloader works.
        sys.argv = ['-m', this_module] + args
    else:
        name = None

    cli.main(args=args, prog_name=name) 
Example #4
Source File: cmd_udp.py    From wio-cli with MIT License 6 votes vote down vote up
def cli(wio, send):
    '''
    Sends a UDP command to the wio device.

    \b
    DOES:
        Support "VERSION", "SCAN", "Blank?", "DEBUG", "ENDEBUG: 1", "ENDEBUG: 0"
        "APCFG: AP\\tPWDs\\tTOKENs\\tSNs\\tSERVER_Domains\\tXSERVER_Domain\\t\\r\\n",
        Note:
        1. Ensure your device is Configure Mode.
        2. Change your computer network to Wio's AP.

    \b
    EXAMPLE:
        wio udp --send [command], send UPD command
    '''
    command = send
    click.echo("UDP command: {}".format(command))
    result = udp.common_send(command)
    if result is None:
        return debug_error()
    else:
        click.echo(result) 
Example #5
Source File: cli.py    From quart with MIT License 6 votes vote down vote up
def get_command(self, ctx: click.Context, name: str) -> click.Command:
        """Return the relevant command given the context and name.

        .. warning::

            This differs substantially from Flask in that it allows
            for the inbuilt commands to be overridden.
        """
        info = ctx.ensure_object(ScriptInfo)
        command = None
        try:
            command = info.load_app().cli.get_command(ctx, name)
        except NoAppException:
            pass
        if command is None:
            command = super().get_command(ctx, name)
        return command 
Example #6
Source File: adapter.py    From django-click with MIT License 6 votes vote down vote up
def __call__(self, func):
        module = sys.modules[func.__module__]

        # Get the command name as Django expects it
        self.name = func.__module__.rsplit(".", 1)[-1]

        # Build the click command
        decorators = [
            click.command(name=self.name, cls=self.cls, **self.kwargs),
        ] + self.get_params(self.name)

        for decorator in reversed(decorators):
            func = decorator(func)

        # Django expects the command to be callable (it instantiates the class
        # pointed at by the `Command` module-level property)...
        # ...let's make it happy.
        module.Command = lambda: func

        return func 
Example #7
Source File: subcommand.py    From pygreynoise with MIT License 6 votes vote down vote up
def analyze(
    context, api_client, api_key, input_file, output_file, output_format, verbose
):
    """Analyze the IP addresses in a log file, stdin, etc."""
    if input_file is None:
        if sys.stdin.isatty():
            output = [
                context.command.get_usage(context),
                (
                    "Error: at least one text file must be passed "
                    "either through the -i/--input_file option or through a shell pipe."
                ),
            ]
            click.echo("\n\n".join(output))
            context.exit(-1)
        else:
            input_file = click.open_file("-")
    if output_file is None:
        output_file = click.open_file("-", mode="w")

    result = api_client.analyze(input_file)
    return result 
Example #8
Source File: cli.py    From recruit with Apache License 2.0 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            # However, we will not do so silently because that would confuse
            # users.
            traceback.print_exc()
        return sorted(rv) 
Example #9
Source File: cli.py    From recruit with Apache License 2.0 6 votes vote down vote up
def main(self, *args, **kwargs):
        # Set a global flag that indicates that we were invoked from the
        # command line interface. This is detected by Flask.run to make the
        # call into a no-op. This is necessary to avoid ugly errors when the
        # script that is loaded here also attempts to start a server.
        os.environ['FLASK_RUN_FROM_CLI'] = 'true'

        if get_load_dotenv(self.load_dotenv):
            load_dotenv()

        obj = kwargs.get('obj')

        if obj is None:
            obj = ScriptInfo(create_app=self.create_app)

        kwargs['obj'] = obj
        kwargs.setdefault('auto_envvar_prefix', 'FLASK')
        return super(FlaskGroup, self).main(*args, **kwargs) 
Example #10
Source File: adapter.py    From django-click with MIT License 6 votes vote down vote up
def execute(self, *args, **kwargs):
        """
        Called when run through `call_command`. `args` are passed through,
        while `kwargs` is the __dict__ of the return value of
        `self.create_parser('', name)` updated with the kwargs passed to
        `call_command`.
        """
        # Remove internal Django command handling machinery
        kwargs.pop("skip_checks", None)
        parent_ctx = click.get_current_context(silent=True)
        with self.make_context("", list(args), parent=parent_ctx) as ctx:
            # Rename kwargs to to the appropriate destination argument name
            opt_mapping = dict(self.map_names())
            arg_options = {
                opt_mapping.get(key, key): value for key, value in six.iteritems(kwargs)
            }

            # Update the context with the passed (renamed) kwargs
            ctx.params.update(arg_options)

            # Invoke the command
            self.invoke(ctx) 
Example #11
Source File: cli.py    From jbox with MIT License 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            pass
        return sorted(rv) 
Example #12
Source File: method_terminal_commands.py    From cellphonedb with MIT License 6 votes vote down vote up
def check_subsampling_params(ctx: Context, argument: Argument, value) -> Any:
    subsampling = ctx.params.get('subsampling')

    if not subsampling and value is not None:
        tpl = 'This parameter ({}) only applies to subsampling, to enable it add `--subsampling` to your command'
        app_logger.error(tpl.format(argument.name))
        ctx.abort()

    if argument.name == 'subsampling_log' and subsampling and value is None:
        app_logger.error('''In order to perform subsampling you need to specify whether to log1p input counts or not:
            to do this specify in your command as --subsampling-log [true|false]''')
        ctx.abort()

    defaults = {
        'subsampling_num_pc': 100,
        'subsampling_num_cells': None
    }

    if subsampling and value is None:
        return defaults.get(argument.name, None)

    return value 
Example #13
Source File: plot_terminal_commands.py    From cellphonedb with MIT License 6 votes vote down vote up
def heatmap_plot(meta_path: str, pvalues_path: str, output_path: str, count_name: str, log_name: str,
                 count_network_name, interaction_count_name, pvalue: float, verbose: bool):
    try:
        r_plotter.heatmaps_plot(meta_file=meta_path,
                                pvalues_file=pvalues_path,
                                output_path=output_path,
                                count_name=count_name,
                                log_name=log_name,
                                count_network_filename=count_network_name,
                                interaction_count_filename=interaction_count_name,
                                pvalue=pvalue)
    except MissingR:
        print('You cannot perform this plot command unless there is a working R setup according to CellPhoneDB specs')
    except RRuntimeException as e:
        app_logger.error(str(e))
    except:
        app_logger.error('Unexpected error')

        if verbose:
            traceback.print_exc(file=sys.stdout)
        else:
            app_logger.error('execute with --verbose to see full stack trace') 
Example #14
Source File: test_utils.py    From isitfit with Apache License 2.0 6 votes vote down vote up
def test_oneInputSetLast(self, ping_matomo):
    """
    # build a fake click command so that the click.prompt will be emulated
    # https://click.palletsprojects.com/en/7.x/testing/?highlight=test#input-streams
    """
    import click
    @click.command()
    def cmd():
      from isitfit.utils import PromptToEmailIfNotRequested
      pte = PromptToEmailIfNotRequested()
      import tempfile
      with tempfile.NamedTemporaryFile() as fh:
        pte.last_email_cl.fn = fh.name # overwrite file to save last-used email
        pte.last_email_cl.set('me@example.com')
        pte.prompt(None)

    # trigger
    from click.testing import CliRunner
    runner = CliRunner()
    result = runner.invoke(cmd, input='\n')
    print(result.__dict__) # in case of exception, this will show details
    assert not result.exception
    assert '[skip]' not in result.output
    assert '[me@example.com]' in result.output 
Example #15
Source File: test_utils.py    From isitfit with Apache License 2.0 6 votes vote down vote up
def test_oneInputNoLast(self, ping_matomo):
    """
    # build a fake click command so that the click.prompt will be emulated
    # https://click.palletsprojects.com/en/7.x/testing/?highlight=test#input-streams
    """
    import click
    @click.command()
    def cmd():
      from isitfit.utils import PromptToEmailIfNotRequested
      pte = PromptToEmailIfNotRequested()
      import tempfile
      with tempfile.NamedTemporaryFile() as fh:
        pte.last_email_cl.fn = fh.name # overwrite file to save last-used email
        pte.prompt(None)

    # trigger
    from click.testing import CliRunner
    runner = CliRunner()
    result = runner.invoke(cmd, input='me@example.com\n')
    print(result.__dict__) # in case of exception, this will show details
    assert not result.exception
    assert '[skip]' in result.output 
Example #16
Source File: test_clickDescendents.py    From isitfit with Apache License 2.0 6 votes vote down vote up
def test_IsitfitOption_worksWithPrompt(runner):
  """
  This test is the working counter-part of test_ClickOption_failsWithPrompt which was expected to fail
  """
  from isitfit.cli.click_descendents import isitfit_option_base

  @click.group()
  def isitfit(): pass

  # Note that in the below, callback is not set
  @click.group()
  @isitfit_option_base('--prompt', default='foo', prompt='my prompt', type=str)
  def cost(prompt): pass

  @click.command()
  def analyze(): pass

  cost.add_command(analyze)
  isitfit.add_command(cost)

  # invoke and assert
  result = runner.invoke(isitfit, ['cost', '--help'])
  assert not result.exception 
Example #17
Source File: cli.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def main(as_module=False):
    this_module = __package__ + '.cli'
    args = sys.argv[1:]

    if as_module:
        if sys.version_info >= (2, 7):
            name = 'python -m ' + this_module.rsplit('.', 1)[0]
        else:
            name = 'python -m ' + this_module

        # This module is always executed as "python -m flask.run" and as such
        # we need to ensure that we restore the actual command line so that
        # the reloader can properly operate.
        sys.argv = ['-m', this_module] + sys.argv[1:]
    else:
        name = None

    cli.main(args=args, prog_name=name) 
Example #18
Source File: cli.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def list_commands(self, ctx):
        self._load_plugin_commands()

        # The commands available is the list of both the application (if
        # available) plus the builtin commands.
        rv = set(click.Group.list_commands(self, ctx))
        info = ctx.ensure_object(ScriptInfo)
        try:
            rv.update(info.load_app().cli.list_commands(ctx))
        except Exception:
            # Here we intentionally swallow all exceptions as we don't
            # want the help page to break if the app does not exist.
            # If someone attempts to use the command we try to create
            # the app again and this will give us the error.
            pass
        return sorted(rv) 
Example #19
Source File: wheel.py    From acsoo with GNU General Public License v3.0 6 votes vote down vote up
def wheel(
    src, requirement, wheel_dir, no_cache_dir, no_index, no_deps, exclude_project=False
):
    """Build wheels for all dependencies found in requirements.txt,
    plus the project in the current directory.

    The main advantage of this command (compared to a regular
    `pip wheel -r requirements.txt -e . --wheel_dir=release --src src`),
    is that it maintains a cache of git dependencies that are pinned with
    a sha1.

    CAUTION: all wheel files are removed from the target directory before
    building.
    """
    do_wheel(
        src, requirement, wheel_dir, no_cache_dir, no_index, no_deps, exclude_project
    ) 
Example #20
Source File: experiment.py    From floyd-cli with Apache License 2.0 6 votes vote down vote up
def status(id):
    """
    View status of all jobs in a project.

    The command also accepts a specific job name.
    """
    if id:
        try:
            experiment = ExperimentClient().get(normalize_job_name(id))
        except FloydException:
            experiment = ExperimentClient().get(id)

        print_experiments([experiment])
    else:
        experiments = ExperimentClient().get_all()
        print_experiments(experiments) 
Example #21
Source File: gui.py    From skan with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_buttons_frame(self, parent):
        buttons = ttk.Frame(master=parent, padding=STANDARD_MARGIN)
        buttons.grid(sticky='nsew')
        actions = [
            ('Choose config', self.choose_config_file),
            ('Choose files', self.choose_input_files),
            ('Choose output folder', self.choose_output_folder),
            ('Run', lambda: asyncio.ensure_future(self.run()))
        ]
        for col, (action_name, action) in enumerate(actions):
            button = ttk.Button(buttons, text=action_name,
                                command=action)
            button.grid(row=0, column=col) 
Example #22
Source File: plot_terminal_commands.py    From cellphonedb with MIT License 6 votes vote down vote up
def dot_plot(means_path: str, pvalues_path: str, output_path: str, output_name: str, rows: str,
             columns: str, verbose: bool):
    try:
        r_plotter.dot_plot(means_path=means_path,
                           pvalues_path=pvalues_path,
                           output_path=output_path,
                           output_name=output_name,
                           rows=rows,
                           columns=columns)
    except MissingR:
        print('You cannot perform this plot command unless there is a working R setup according to CellPhoneDB specs')
    except RRuntimeException as e:
        app_logger.error(str(e))
    except:
        app_logger.error('Unexpected error')

        if verbose:
            traceback.print_exc(file=sys.stdout)
        else:
            app_logger.error('execute with --verbose to see full stack trace') 
Example #23
Source File: cmdl.py    From a2ml with Apache License 2.0 5 votes vote down vote up
def cmdl(ctx):
    """A2ML command line interface.""" 
Example #24
Source File: pomodoro-client.py    From i3-gnome-pomodoro with GNU General Public License v3.0 5 votes vote down vote up
def activate_workspace(i3, name):
    i3.command("workspace %s" % name) 
Example #25
Source File: sidomo.py    From sidomo with The Unlicense 5 votes vote down vote up
def run(self, command):
        """Just like 'docker run CMD'.

        This is a generator that yields lines of container output.
        """
        exec_id = client.exec_create(
            container=self.container_id,
            cmd=command,
            stdout=self.stdout,
            stderr=self.stderr
        )['Id']

        for line in client.exec_start(exec_id, stream=True):
            yield line 
Example #26
Source File: run_benchmarks.py    From garage with MIT License 5 votes vote down vote up
def _echo_run_names(header, d):
    """Echo run names to the command line.

    Args:
        header (str): The header name.
        d (dict): The dict containing benchmark options.

    """
    click.echo('-----' + header + '-----')
    for name in d:
        click.echo(name)
    click.echo() 
Example #27
Source File: run_benchmarks.py    From garage with MIT License 5 votes vote down vote up
def cli():
    """The main command group.""" 
Example #28
Source File: tag.py    From acsoo with GNU General Public License v3.0 5 votes vote down vote up
def tag(ctx, force, src, requirement, yes, dry_run):
    """ Tag the current project and its VCS requirements.

    This command verifies everything has been committed, then
    performs git tag, git push and acsoo tag_requirements.
    """
    do_tag(ctx.obj["config"], force, src, requirement, yes, dry_run) 
Example #29
Source File: init.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def validate_boards(ctx, param, value):  # pylint: disable=W0613
    unknown_boards = set(value) - set(get_boards().keys())
    try:
        assert not unknown_boards
        return value
    except AssertionError:
        raise click.BadParameter(
            "%s. Please search for the board types using "
            "`platformio boards` command" % ", ".join(unknown_boards)) 
Example #30
Source File: ci.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def validate_boards(ctx, param, value):  # pylint: disable=W0613
    unknown_boards = set(value) - set(get_boards().keys())
    try:
        assert not unknown_boards
        return value
    except AssertionError:
        raise click.BadParameter(
            "%s. Please search for the board types using "
            "`platformio boards` command" % ", ".join(unknown_boards))