Python click.group() Examples
The following are 30
code examples of click.group().
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: test_clickDescendents.py From isitfit with Apache License 2.0 | 7 votes |
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 #2
Source File: test_basic.py From click-repl with MIT License | 7 votes |
def test_completion(): @click.group() def root_command(): pass @root_command.group() def first_level_command(): pass @first_level_command.command() def second_level_command_one(): pass @first_level_command.command() def second_level_command_two(): pass c = ClickCompleter(root_command) completions = list(c.get_completions(Document(u"first_level_command "))) assert set(x.text for x in completions) == set( [u"second_level_command_one", u"second_level_command_two"] )
Example #3
Source File: cci.py From CumulusCI with BSD 3-Clause "New" or "Revised" License | 6 votes |
def error(): """ Get or share information about an error If you'd like to dig into an error more yourself, you can get the last few lines of context about it from `cci error info`. If you'd like to submit it to a developer for conversation, you can use the `cci error gist` command. Just make sure that your GitHub access token has the 'create gist' scope. For more information on working with errors in CumulusCI visit: https://cumulusci.readthedocs.io/en/latest/features.html#working-with-errors """ # Commands for group: project
Example #4
Source File: cci.py From CumulusCI with BSD 3-Clause "New" or "Revised" License | 6 votes |
def service_info(runtime, service_name, plain): try: plain = plain or runtime.global_config.cli__plain_output service_config = runtime.keychain.get_service(service_name) service_data = [["Key", "Value"]] service_data.extend( [ [click.style(k, bold=True), str(v)] for k, v in service_config.config.items() ] ) wrap_cols = ["Value"] if not plain else None service_table = CliTable(service_data, title=service_name, wrap_cols=wrap_cols) service_table._table.inner_heading_row_border = False service_table.echo(plain) except ServiceNotConfigured: click.echo( "{0} is not configured for this project. Use service connect {0} to configure.".format( service_name ) ) # Commands for group: org
Example #5
Source File: test_command_collection.py From click-repl with MIT License | 6 votes |
def test_completion(): @click.group() def foo_group(): pass @foo_group.command() def foo_cmd(): pass @click.group() def foobar_group(): pass @foobar_group.command() def foobar_cmd(): pass c = ClickCompleter(click.CommandCollection(sources=[foo_group, foobar_group])) completions = list(c.get_completions(Document(u"foo"))) assert set(x.text for x in completions) == set([u"foo_cmd", u"foobar_cmd"])
Example #6
Source File: groups.py From Paradrop with Apache License 2.0 | 6 votes |
def list_groups(ctx): """ (deprecated) List user groups. Please use `pdtools cloud list-groups`. """ url = ctx.obj['pdserver_url'] + "/api/groups" result = pdserver_request('GET', url) groups = result.json() for group in groups: print("{} {}".format(group['_id'], group['name'])) print(" Users:") for user_id in group['users']: print(" {}".format(user_id)) print(" Routers:") for router_id in group['routers']: print(" {}".format(router_id))
Example #7
Source File: cmd_address.py From kamcli with GNU General Public License v2.0 | 6 votes |
def address_list(ctx, mode, group): """Show details for address records in memory \b Parameters: <group> - address group """ if mode == "all": command_ctl(ctx, "permissions.addressDump", []) command_ctl(ctx, "permissions.subnetDump", []) command_ctl(ctx, "permissions.domainDump", []) elif mode == "addresses": command_ctl(ctx, "permissions.addressDump", []) elif mode == "subnets": command_ctl(ctx, "permissions.subnetDump", []) elif mode == "domains": command_ctl(ctx, "permissions.domainDump", []) else: command_ctl(ctx, "permissions.addressDump", [])
Example #8
Source File: cmd_group.py From kamcli with GNU General Public License v2.0 | 6 votes |
def group_grant(ctx, userid, groupid): """Add a user into a group (grant privilege) \b Parameters: <userid> - username, AoR or SIP URI for subscriber <groupid> - group name """ udata = parse_user_spec(ctx, userid) ctx.vlog( "Adding user [%s@%s] in group [%s]", udata["username"], udata["domain"], groupid, ) e = create_engine(ctx.gconfig.get("db", "rwurl")) e.execute( "insert into grp (username, domain, grp) values (%s, %s, %s)", udata["username"], udata["domain"], groupid, )
Example #9
Source File: __init__.py From gshell with MIT License | 6 votes |
def cmd_share(filename, role, type, email, domain, discoverable): if type in ['user', 'group'] and email is None: print('--email is required for user or group type.') sys.exit(1) elif type == 'domain' and domain is None: print('--domain is required for domain type.') sys.exit(1) config_dir = _get_current_config_dir() id = get_id_by_path(filename) cmd = '{exe} --config {config} share'.format( exe=DRIVE_EXE, config=config_dir) if role: cmd += ' --role {role}'.format(role=role) if type: cmd += ' --type {type}'.format(type=type) if email: cmd += ' --email {email}'.format(email=email) if domain: cmd += ' --domain {domain}'.format(domain=domain) if discoverable: cmd += ' --discoverable' # if revoke: # cmd += ' --revoke' cmd += ' {id}'.format(id=id) subprocess.call(cmd, shell=True)
Example #10
Source File: test_clickDescendents.py From isitfit with Apache License 2.0 | 6 votes |
def test_IsitfitOptionProfile_ok(runner): from isitfit.cli.click_descendents import isitfit_option_profile @click.group() def isitfit(): pass @click.group() @isitfit_option_profile() 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 #11
Source File: test_clickDescendents.py From isitfit with Apache License 2.0 | 6 votes |
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 #12
Source File: cmd_group.py From kamcli with GNU General Public License v2.0 | 5 votes |
def group_revoke(ctx, userid, groupid): """Remove a user from groups (revoke privilege) \b Parameters: <userid> - username, AoR or SIP URI for subscriber <groupid> - group name """ udata = parse_user_spec(ctx, userid) ctx.log( "Removing ACL for user [%s@%s]", udata["username"], udata["domain"] ) e = create_engine(ctx.gconfig.get("db", "rwurl")) if not groupid: e.execute( "delete from grp where username=%s and domain=%s", udata["username"], udata["domain"], ) else: e.execute( "delete from grp where username=%s and domain=%s and grp=%s", udata["username"], udata["domain"], groupid, )
Example #13
Source File: cci.py From CumulusCI with BSD 3-Clause "New" or "Revised" License | 5 votes |
def cli(): """Top-level `click` command group."""
Example #14
Source File: cmd_db.py From kamcli with GNU General Public License v2.0 | 5 votes |
def db_create_tables_group(ctx, directory, gname): """Create the group of database tables for a specific extension \b Parameters: <gname> - the name of the group of tables """ ldirectory = "" if len(directory) > 0: ldirectory = directory e = create_engine(ctx.gconfig.get("db", "rwurl")) fpath = ldirectory + "/" + gname + "-create.sql" dbutils_exec_sqlfile(ctx, e, fpath)
Example #15
Source File: cmd_group.py From kamcli with GNU General Public License v2.0 | 5 votes |
def group_show(ctx, oformat, ostyle, userid): """Show details for subscribers \b Parameters: [<userid>] - username, AoR or SIP URI for subscriber - it can be a list of userids - if not provided then all subscribers are shown """ if not userid: ctx.vlog("Showing all records") e = create_engine(ctx.gconfig.get("db", "rwurl")) res = e.execute("select * from grp") ioutils_dbres_print(ctx, oformat, ostyle, res) else: for u in userid: udata = parse_user_spec(ctx, u) ctx.vlog( "Showing group membership for user [%s@%s]", udata["username"], udata["domain"], ) e = create_engine(ctx.gconfig.get("db", "rwurl")) res = e.execute( "select * from grp where username=%s and domain=%s", udata["username"], udata["domain"], ) ioutils_dbres_print(ctx, oformat, ostyle, res)
Example #16
Source File: shape.py From OpenNGC with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
def create_surfaces(software): """Generate the surfaces catalog file for the given software. Args: software: the software you would like to generate the catalog for. """ files_list = [] for (dirpath, dirnames, filenames) in walk('objects'): files_list.extend(filenames) output = open(f'surfaces_{software}.dat', 'w') print(f'Processing {len(files_list)} object files...') for dso in files_list: match = re.search(r'_lv(\d).', dso) level = match.group(1) if match is not None else '2' with open(join('objects', dso), 'r') as f: reader = csv.DictReader(f, delimiter='\t') points = [[], ] shape_nbr = 0 for line in reader: points[shape_nbr].append((float(line["RAJ2000"]), float(line["DEJ2000"]))) if line["Cont_Flag"] == '*': points.append([]) shape_nbr += 1 for shape in points: if shape: outline = LineString(shape).simplify(shape_precision) points_counter = len(outline.coords) for idx, p in enumerate(outline.coords, 1): output.write(eval(software)(dso, points_counter, idx, p, level))
Example #17
Source File: shape.py From OpenNGC with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
def create_outlines(software, level): """Generate the outlines catalog file for the given software. Args: software: the software you would like to generate the catalog for. level: the brightness level you want to use to calculate the shape. If you don't enter any value, the catalog file will contain all levels. """ files_list = [] for (dirpath, dirnames, filenames) in walk('objects'): if level is not None: for fname in filenames: if f'_lv{level}.' in fname or not f'_lv' in fname: files_list.append(fname) else: files_list.extend(filenames) output = open(f'outlines_{software}.dat', 'w') print(f'Processing {len(files_list)} object files...') for dso in files_list: match = re.search(r'_lv(\d).', dso) level = match.group(1) if match is not None else '2' with open(join('objects', dso), 'r') as f: reader = csv.DictReader(f, delimiter='\t') points = [[], ] shape_nbr = 0 for line in reader: points[shape_nbr].append((float(line["RAJ2000"]), float(line["DEJ2000"]))) if line["Cont_Flag"] == '*': points.append([]) shape_nbr += 1 for shape in points: if shape: outline = LineString(shape).simplify(shape_precision) points_counter = len(outline.coords) for idx, p in enumerate(outline.coords, 1): output.write(eval(software)(dso, points_counter, idx, p, level))
Example #18
Source File: hello_example.py From PyCon2019-Click-Tutorial with Mozilla Public License 2.0 | 5 votes |
def cli(): """Command group."""
Example #19
Source File: download.py From sciwing with MIT License | 5 votes |
def download(): """ Download group of commands that helps in downloading to the user machine """ pass
Example #20
Source File: cmd_db.py From kamcli with GNU General Public License v2.0 | 5 votes |
def db_create_tables_list(ctx, directory, group): dbtype = ctx.gconfig.get("db", "type") if dbtype != "mysql": ctx.vlog("Database type [%s] not supported yet", dbtype) return ldirectory = "" if len(directory) > 0: ldirectory = directory e = create_engine(ctx.gconfig.get("db", "rwurl")) db_create_group(ctx, e, ldirectory, group)
Example #21
Source File: __main__.py From python-viptela with GNU General Public License v3.0 | 5 votes |
def auth(self): if self.__auth is None: self.__auth = Authentication(host=self.host, user=self.username, password=self.password).login() return self.__auth # @click.group(cls=CatchAllExceptions)
Example #22
Source File: indexing.py From ms_deisotope with Apache License 2.0 | 5 votes |
def _mount_group(group): try: for name, command in group.commands.items(): cli.add_command(command, name) except Exception as e: click.secho("%r occurred while loading additional tools from %r" % (e, group), err=True, fg='yellow')
Example #23
Source File: cli.py From stakkr with Apache License 2.0 | 5 votes |
def stakkr(ctx: Context, config=None, debug=False, verbose=True): """Click group, set context and main object.""" from stakkr.actions import StakkrActions ctx.obj['CONFIG'] = config ctx.obj['DEBUG'] = debug ctx.obj['VERBOSE'] = verbose ctx.obj['STAKKR'] = StakkrActions(ctx.obj)
Example #24
Source File: shipyard.py From batch-shipyard with MIT License | 5 votes |
def fs_disks_list(ctx, resource_group, restrict_scope): """List managed disks in resource group""" ctx.initialize_for_fs() convoy.fleet.action_fs_disks_list( ctx.compute_client, ctx.config, resource_group, restrict_scope)
Example #25
Source File: click_descendents.py From isitfit with Apache License 2.0 | 5 votes |
def isitfit_group(name=None, **attrs): """ Overrides click.decorators.group to use the class IsitfitGroup """ attrs.setdefault('cls', IsitfitGroup) return click.command(name, **attrs) # Inherit from click's usageError since click can handle it automatically # https://click.palletsprojects.com/en/7.x/exceptions/
Example #26
Source File: click_descendents.py From isitfit with Apache License 2.0 | 5 votes |
def pingOnError(ctx, error): # if not dict yet, i.e. before the cli.core.cli_core group # Important to keep track of the didPing variable if ctx.obj is None: return # check if the error's ping was done didPing = 'unhandled_error_pinged' in ctx.obj.keys() if didPing: return # send to sentry.io via isitfit.io (check usage of sentry_proxy in cli.core) from sentry_sdk import capture_exception capture_exception(error) # proceed to ping matomo about the error (to be deprecated in full in favor of sentry) from isitfit.utils import ping_matomo exception_type = type(error).__name__ # https://techeplanet.com/python-catch-all-exceptions/ exception_str = "" try: exception_str = str(error) except: pass ping_matomo("/error/unhandled/%s?message=%s"%(exception_type, exception_str)) # save a flag saying that the error sent a ping # Note that it is not necessary to do more than that, such as storing a list of pinged errors, # because there will be exactly one error raise at most before the program fails ctx.obj['unhandled_error_pinged'] = True
Example #27
Source File: cci.py From CumulusCI with BSD 3-Clause "New" or "Revised" License | 5 votes |
def project_dependencies(runtime): dependencies = runtime.project_config.get_static_dependencies() for line in runtime.project_config.pretty_dependencies(dependencies): click.echo(line) # Commands for group: service
Example #28
Source File: cci.py From CumulusCI with BSD 3-Clause "New" or "Revised" License | 5 votes |
def org_shell(runtime, org_name, script=None, python=None): org_name, org_config = runtime.get_org(org_name) org_config.refresh_oauth_token(runtime.keychain) sf = get_simple_salesforce_connection(runtime.project_config, org_config) sf_helpers = SimpleSalesforceUIHelpers(sf) globals = { "sf": sf, "org_config": org_config, "project_config": runtime.project_config, "help": CCIHelp(), "query": sf_helpers.query, "describe": sf_helpers.describe, } if script: if python: raise click.UsageError("Cannot specify both --script and --python") runpy.run_path(script, init_globals=globals) elif python: exec(python, globals) else: code.interact( banner=f"Use `sf` to access org `{org_name}` via simple_salesforce\n" + "Type `help` for more information about the cci shell.", local=globals, ) # Save the org config in case it was modified runtime.keychain.set_org(org_config) # Commands for group: task
Example #29
Source File: __init__.py From go2mapillary with GNU General Public License v3.0 | 5 votes |
def iter_lines(lines): """Iterate over lines of input, stripping and skipping.""" for line in lines: line = line.strip() if line: yield line # The CLI command group.
Example #30
Source File: piku.py From piku with MIT License | 5 votes |
def expandvars(buffer, env, default=None, skip_escaped=False): """expand shell-style environment variables in a buffer""" def replace_var(match): return env.get(match.group(2) or match.group(1), match.group(0) if default is None else default) pattern = (r'(?<!\\)' if skip_escaped else '') + r'\$(\w+|\{([^}]*)\})' return sub(pattern, replace_var, buffer)