def _parse_env_subcommands(self): configuration_names = self.user_config.configuration_names def name_completer(prefix, *args, **kwargs): return (n for n in configuration_names if n.startswith(prefix)) @argh.named('use') def _use_command(name): if name not in configuration_names: raise argh.CommandError( 'No such configuration: {}'.format(name)) self.user_config.current = name argh.arg('name', completer=name_completer)(_use_command) @argh.named('remove') def _remove_command(name): if name not in configuration_names: raise argh.CommandError('No such configuration: {}') self.user_config.remove_configuration(name) argh.arg('name', completer=name_completer)(_remove_command) @argh.named('list') def _list_command(): return '\n'.join(configuration_names) return [_use_command, _remove_command, _list_command]
def _parse_env_subcommands(self): configuration_names = self.user_config.configuration_names def name_completer(prefix, *args, **kwargs): return (n for n in configuration_names if n.startswith(prefix)) @argh.named('use') def _use_command(name): if name not in configuration_names: raise argh.CommandError('No such configuration: {}' .format(name)) self.user_config.current = name argh.arg('name', completer=name_completer)(_use_command) @argh.named('remove') def _remove_command(name): if name not in configuration_names: raise argh.CommandError('No such configuration: {}') self.user_config.remove_configuration(name) argh.arg('name', completer=name_completer)(_remove_command) @argh.named('list') def _list_command(): return '\n'.join(configuration_names) return [_use_command, _remove_command, _list_command]
def _add_args_to_func(self, func, args, skip_env): for arg in reversed(args): name = arg.pop('name') completer = arg.pop('completer', None) if completer: completer = module.load_attribute(completer) completer = Completer(None if skip_env else self._load_env, completer) arg['completer'] = completer name = name if isinstance(name, list) else [name] argh.arg(*name, **arg)(func)
def install_args(f): """Apply all the args that are used by `cfy_manager install`""" args = [ argh.arg('--clean-db', help=CLEAN_DB_HELP_MSG), argh.arg('--private-ip', help=PRIVATE_IP_HELP_MSG), argh.arg('--public-ip', help=PUBLIC_IP_HELP_MSG), argh.arg('-a', '--admin-password', help=ADMIN_PASSWORD_HELP_MSG) ] for arg in args: f = arg(f) return f
def _parse_env_create_command(self): env_create = self.config.env_create @argh.expects_obj @argh.named('create') def func(args): if (self.user_config.current == args.name and self.user_config.storage_dir and not args.reset): raise argh.CommandError('storage dir already configured. pass ' '--reset to override.') storage_dir = args.storage_dir or os.getcwd() self.user_config.current = args.name self.user_config.editable = args.editable self.user_config.storage_dir = storage_dir self.user_config.storage_dir.mkdir_p() self._create_inputs(args, env_create.get('inputs', {})) self.user_config.macros_path.touch() after_env_create_func = self.config.hooks.after_env_create if after_env_create_func: after_env_create = module.load_attribute(after_env_create_func) after_env_create(self, **vars(args)) self._add_args_to_func(func, env_create.get('args', []), skip_env=True) argh.arg('-s', '--storage-dir')(func) argh.arg('-r', '--reset', default=False)(func) argh.arg('-e', '--editable', default=False)(func) argh.arg('-n', '--name', default='main')(func) return func
def call_function(f: Callable): parser = argh.helpers.ArghParser() parser.add_argument( 'config_file', type=argparse.FileType('r'), help='path to config file with PVE credentials', ) parser.add_argument( '--section', help='config section to use', action='append', ) parser.set_default_command( argh.arg( '--pve', help=argparse.SUPPRESS, default=argparse.SUPPRESS, )(f)) args = parser.parse_args() var_args = dict(vars(args)) del var_args['config_file'] del var_args['section'] del var_args['_functions_stack'] import configparser config = configparser.ConfigParser() config.read_file(args.config_file) problems = tuple( itertools.chain.from_iterable( f(ProxmoxAPI(**config[section]), **var_args) for section in args.section or config.sections())) handle_result(merge_results(problems))
def environment_db_path(): """Add a default value to the `db_path` positional argument, based on the `LDB_PATH` environment variable, and fail elegantly if not.""" try: return arg( "db_path", default=os.environ["LDB_PATH"], nargs="?", help="The path of the LabbookDB database file to query. " "We detect that your `LDB_PATH` environment variable is set to `{}` in this prompt. " "This is automatically used by LabbookDB if no custom value is specified." .format(os.environ["LDB_PATH"]), ) except KeyError: return arg( "db_path", help="The path of the LabbookDB database file to query. " "We detect that your `LDB_PATH` environment variable IS NOT set in this prompt. " "This environment variable can be automatically used by LabbookDB if no custom value is specified.", )
def env_arg(arg_name, env_var, help='', **kwargs): """ Decorator that declares a command line argument that if not supplied the value will be taken from an environment variable Args: arg_name (str): A string containing the command line flag. e.g. --my-flag env_var (str): The name of the environment variable help (str): Help text for argument **kwargs: Additional arguments that will be passed to argh.arg """ help += ' If not provided, it will be taken from the environment variable %s' % env_var return argh.arg(arg_name, env_var_name=env_var, action=_EnvDefault, help=help, **kwargs)
def install_args(f): """Apply all the args that are used by `cfy_manager install`""" args = [ argh.arg('--clean-db', help=CLEAN_DB_HELP_MSG), argh.arg('--private-ip', help=PRIVATE_IP_HELP_MSG), argh.arg('--public-ip', help=PUBLIC_IP_HELP_MSG), argh.arg('-a', '--admin-password', help=ADMIN_PASSWORD_HELP_MSG), argh.arg('--join-cluster', help=JOIN_CLUSTER_HELP_MSG), argh.arg('--database-ip', help=DATABASE_IP_HELP_MSG), argh.arg('--postgres-password', help=POSTGRES_PASSWORD_HELP_MSG) ] for arg in args: f = arg(f) return f
def arg_verbose(func): """ This is a decorator that adds --verbose command line argument to a command. If the command supports the argument, the command must correctly initialize reportclient, because we want to propagate the verbosity to called functions. """ @functools.wraps(func) def abrt_wrapper(args): if 'verbose' in args: reportclient.verbose += args.verbose set_verbosity(reportclient.verbose) return func(args) argh_wrapper = arg('-v', '--verbose', action='count', default=0, help=_('Print verbose information')) return argh_wrapper(abrt_wrapper)
def file_arg(*args: Any, mode: str = "r", **kwargs: Any) -> Any: return argh.arg(*args, **kwargs, type=argparse.FileType(mode))
""" import datetime, os from requests.exceptions import HTTPError, ConnectionError, InvalidSchema from argh import arg, ArghParser from argh.exceptions import CommandError from gestus_client import logging_handler from gestus_client import __version__ as client_version from gestus_client.config import GestusConfig from gestus_client.client import GestusClient, WebsitePostException, ENVIRONMENT_KIND_CHOICES, ENVIRONMENT_KIND_KEYS # Available common options for all commands cmd_user_opt = arg('-u', '--user', default=None, help="Username to connect to the service") cmd_password_opt = arg('-p', '--password', default=None, help="Password to connect to the service") cmd_host_opt = arg('-o', '--host', default=None, help="Http(s) address to connect to the service") cmd_config_opt = arg('-c', '--config', default='gestus.cfg', help="Path to the client config file") cmd_passive_opt = arg('--passive', default=False,
""" import datetime, os from requests.exceptions import HTTPError, ConnectionError, InvalidSchema from argh import arg, ArghParser from argh.exceptions import CommandError from po_projects_client import logging_handler from po_projects_client import __version__ as client_version from po_projects_client.config import POProjectConfig from po_projects_client.client import ProjectDoesNotExistException, PotDoesNotExistException, POProjectClient # Available common options for all commands cmd_user_opt = arg('-u', '--user', default=None, help="Username to connect to the service") cmd_password_opt = arg('-p', '--password', default=None, help="Password to connect to the service") cmd_host_opt = arg('-o', '--host', default=None, help="Http(s) address to connect to the service") cmd_config_opt = arg('-c', '--config', default='po_projects.cfg', help="Path to the client config file") cmd_passive_opt = arg('--passive', default=False,
"offline by stopping its service or shutting down its host.") DB_NODE_ADDRESS_HELP_MSG = ("Address of target DB cluster node.") DB_NODE_FORCE_HELP_MSG = ( "Force removal of cluster node even if it is the master.") DB_SHELL_DBNAME_HELP_MSG = ("Which DB to connect to using DB shell") DB_SHELL_QUERY_HELP_MSG = ( "Optional query to run with the DB shell. If this is provided, the query " "will be run and then the command will exit.") VALIDATE_HELP_MSG = ( "Validate the provided certificates. If this flag is on, then the " "certificates will only be validated and not replaced.") INPUT_PATH_MSG = ("The replace-certificates yaml configuration file path.") config_arg = argh.arg('-c', '--config-file', action='append', default=None, help=CONFIG_FILE_HELP_MSG) @argh.decorators.arg('-s', '--sans', help=TEST_CA_GENERATE_SAN_HELP_TEXT, required=True) def generate_test_cert(**kwargs): """Generate keys with certificates signed by a test CA. Not for production use. """ setup_console_logger() sans = kwargs['sans'].split(',') if not os.path.exists(TEST_CA_CERT_PATH): print('CA cert not found, generating CA certs.')
""" import datetime, os from requests.exceptions import HTTPError, ConnectionError, InvalidSchema from argh import arg, ArghParser from argh.exceptions import CommandError from po_projects_client import logging_handler from po_projects_client import __version__ as client_version from po_projects_client.config import POProjectConfig from po_projects_client.client import ProjectDoesNotExistException, PotDoesNotExistException, POProjectClient # Available common options for all commands cmd_user_opt = arg('-u', '--user', default=None, help="Username to connect to the service") cmd_password_opt = arg('-p', '--password', default=None, help="Password to connect to the service") cmd_host_opt = arg('-o', '--host', default=None, help="Http(s) address to connect to the service") cmd_config_opt = arg('-c', '--config', default='po_projects.cfg', help="Path to the client config file") cmd_passive_opt = arg('--passive', default=False, action='store_true', help="Disable config saving") cmd_loglevel_opt = arg('-l', '--loglevel', default='info', choices=['debug','info','warning','error','critical'], help="The minimal verbosity level to limit logs output") cmd_logfile_opt = arg('--logfile', default=None, help="A filepath that if setted, will be used to save logs output") cmd_timer_opt = arg('-t', '--timer', default=False, action='store_true', help="Display elapsed time at the end of execution") cmd_projectslug_opt = arg('--project_slug', default=None, help="Project slug name") cmd_localepath_opt = arg('--locale_path', default=None, help="Path to the locale directory") cmd_kind_opt = arg('--kind', default='django', help="Kind of message catalog", choices=['django','messages']) cmd_djangodefaultlocale_opt = arg('--django_default_locale', default=None, help="Default locale used to generate a temporary POT file") class CliInterfaceBase(object): """
from . import rcontrol_all from . import listout from . import colors from . import version from . import work from . import times import Cheetah.Template from Cheetah.Template import Template as CheetahTemplate TOOL_NAME = "poni" # common arguments arg_full_match = argh.arg("-M", "--full-match", default=False, dest="full_match", action="store_true", help="require full regexp match") arg_nodes_only = argh.arg("-N", "--nodes", default=False, dest="nodes_only", action="store_true", help="apply only to nodes (not systems)") arg_systems_only = argh.arg("-S", "--systems", default=False, dest="systems_only", action="store_true", help="apply only to systems (not nodes)") arg_verbose = argh.arg("-v", "--verbose", default=False, action="store_true", help="verbose output") arg_path_prefix = argh.arg('--path-prefix', type=str, default="", help='additional prefix for all deployed files') arg_target_nodes_0_to_n = argh.arg('nodes', type=str, help='target nodes (regexp)', nargs="?") arg_target_nodes = argh.arg('nodes', type=str, help='target nodes (regexp)') arg_host_access_method = argh.arg("-m", "--method",
def arg_flag(*args, **kwargs): return argh.arg(*args, default=False, action="store_true", **kwargs)
# Command line interface to deployment from __future__ import print_function import sys import logging import argh from digitalmarketplace.deploy import aws, git proxy_env_arg = argh.arg( '-e', '--proxy-env', type=lambda value: filter(None, map(str.strip, value.split(','))), default="", help="Comma separated list of environment variables to proxy to the " + "configuration template") @argh.arg('db_name', help='Database name') @argh.arg('db_username', help='Master database username') @argh.arg('db_password', help='Master database password') @proxy_env_arg def bootstrap(db_name, db_username, db_password, proxy_env=None, region=None): """Create a new application with an S3 bucket and core environments""" aws.get_client(region).bootstrap(proxy_env, db_name, db_username, db_password) def create_version(version_label, region=None): """Create a new version of the application from the current HEAD""" aws.get_client(region).create_version(version_label)
# out_file.write(normalizedFrame) cv.imshow('frame', imgout) if cv.waitKey(5) & 0xFF == ord('q'): break except Exception as err: msg = '{}: Failed!!! line:{} err:{}'.format(fn, myerror.lineno(), err) log.error(msg) ############################## # fromframefile # Find lines for image that was captured from one frame on disk ############################## #@argh.arg('fnamearr', nargs='+', type=str, help='Array of TIF file names of the images' ) argh.arg('fname', help='File name to capture the image from') def fromframefile(fname): ''' Capture image from frame and find lines''' fn = 'fromframefile()' log = mylog.configure_logging('fromframefile', "/tmp/findlines_algo.log") try: log.info('{}: START'.format(fn)) #log.info('{}: ##############################'.format(fn)) #log.info('{}: \tfnamearr:{}'.format(fn, fnamearr)) #log.info('{}: ##############################'.format(fn)) obj = AlgoFindLines(log=log, isfromros=False) frame = cv.imread(fname)
from __future__ import print_function import json from argh import ArghParser, arg from ghtools import cli from ghtools.github.organisation import Organisation parser = ArghParser(description="Interact with a GitHub organisation") parser.add_argument("org", help="Organisation identifier " "(e.g. rails, enterprise:mycorp)") json_arg = arg("-j", "--json", default=False, action="store_true", help="Print full JSON representations") @json_arg def repos(args): """ Print a list of organisation repositories """ with cli.catch_api_errors(): org = Organisation(args.org) for repo in org.list_repos(): if args.json: print(json.dumps(repo, indent=2)) else: print(repo["name"]) parser.add_commands([repos])
from __future__ import print_function import json from argh import ArghParser, arg from ghtools import cli from ghtools.github.organisation import Organisation parser = ArghParser(description="Interact with a GitHub organisation") parser.add_argument('org', help='Organisation identifier ' '(e.g. rails, enterprise:mycorp)') json_arg = arg('-j', '--json', default=False, action='store_true', help='Print full JSON representations') @json_arg def repos(args): """ Print a list of organisation repositories """ with cli.catch_api_errors(): org = Organisation(args.org) for repo in org.list_repos(): if args.json: print(json.dumps(repo, indent=2)) else:
"""Simple decorator to add function to ``COMMANDS`` list The purpose of this decorator is to make the definition of commands simpler by reducing duplication, it is purely a convenience. :param func func: Function to wrap :rtype: func :returns: Original function """ COMMANDS.append(func) return func # Convenience wrappers for defining command arguments # pylint: disable-msg=C0103 bugs_arg = argh.arg("bugs", nargs="+", type=int, help="bug number(s) to operate on") message_arg = argh.arg("-m", "--message", help="comment text") order_arg = argh.arg("-o", "--order", default="number", choices=["number", "updated", "votes"], help="sort order for listing bugs") states_arg = argh.arg("-s", "--state", default="open", choices=["open", "closed", "all"], help="state of bugs to operate on") stdin_arg = argh.arg("--stdin", default=False, help="read message from standard input") title_arg = argh.arg("title", help="title for the new bug", nargs="?")
import csv import re import spotipy import sys import io from argh import arg, named, CommandError from .config import read_config from .spotipyutil import prompt_for_user_token SPOTIFY_API_SCOPE = 'user-library-read' USERNAME_ARG = arg( '--username', help='Your Spotify user name', default=read_config().get("Spotify", "username") ) CLIENT_ID_ARG = arg( '--client-id', default=read_config().get("Spotify", "client-id") ) CLIENT_SECRET_ARG = arg( '--client-secret', default=read_config().get("Spotify", "client-secret") ) REDIRECT_URI_ARG = arg( '--redirect-uri', default=read_config().get("Spotify", "redirect-uri") )
""" Creates a single decorator that applies multiple argh.arg decorators for commands with a common set of arguments. Args: *arg_defs (list): List of decorators to apply """ def decorator(fn): for arg_def in arg_defs: arg_def(fn) return fn return decorator sql_args = arg_group( argh.arg('--sql-host', default='localhost', help='hostname of the SQL server'), argh.arg('--sql-user', default='mpf', help='username used to log in to the SQL server'), argh.arg('--sql-password', default='password', help='password used to log in to the SQL server'), argh.arg('--skip-sql-start', default=False, help='do not start SQL server if not already running') ) def has_whitespace(string): return any(ch.isspace() for ch in string) class VerifyNoWhiteSpace(argparse.Action): """ Ensures that a command line argument does not contain whitespace. Exits with a warning if the argument contains whitespace"""
def arg_target_nodes(method): b = argh.arg('nodes', type=str, help='target nodes (regexp)') return arg_exclude_nodes(b(method))
if err.returncode == 1: return False raise def service_status(self, service_name): return self.check_call(['service', service_name, 'status']) def start_service(self, service_name): self.check_call(['sudo', 'service', service_name, 'start']) def stop_service(self, service_name): self.check_call(['sudo', 'service', service_name, 'stop']) sys_args = mpf_util.arg_group( argh.arg('-v', '--verbose', default=False, help='Show output from called commands'), argh.arg('--activemq-bin', default='/opt/activemq/bin/activemq', help='path to ActiveMQ binary'), argh.arg('--redis-server-bin', default='redis-server', help='path to redis-server binary'), argh.arg('--redis-cli-bin', default='redis-cli', help='path to redis-cli binary'), argh.arg('--redis-conf', default='/etc/redis.conf', help='path to redis.conf file'), argh.arg('--catalina', default='/opt/apache-tomcat/bin/catalina.sh', help='path to catalina.sh'), argh.arg('--node-manager-port', default=8008, help='port number that the Node Manager listens on'),
TOOL_NAME = "poni" def arg_flag(*args, **kwargs): return argh.arg(*args, default=False, action="store_true", **kwargs) # common arguments arg_full_match = arg_flag("-M", "--full-match", dest="full_match", help="require full regexp match") arg_nodes_only = arg_flag("-N", "--nodes", dest="nodes_only", help="apply only to nodes (not systems)") arg_systems_only = arg_flag("-S", "--systems", dest="systems_only", help="apply only to systems (not nodes)") arg_verbose = arg_flag("-v", "--verbose", help="verbose output") arg_quiet = arg_flag("-q", "--quiet", help="do not show remote command output") arg_path_prefix = argh.arg('--path-prefix', type=str, default="", help='additional prefix for all deployed files') arg_exclude_nodes = argh.arg('--exclude', type=str, metavar="PATTERN", help='exclude node pattern') def arg_target_nodes_0_to_n(method): b = argh.arg('nodes', type=str, help='target nodes (regexp)', nargs="?") return arg_exclude_nodes(b(method)) def arg_target_nodes(method): b = argh.arg('nodes', type=str, help='target nodes (regexp)') return arg_exclude_nodes(b(method)) arg_host_access_method = argh.arg("-m", "--method", choices=rcontrol_all.METHODS.keys(), help="override host access method") arg_output_dir = argh.arg("-o", "--output-dir", metavar="DIR", type=path, help="write command output to files in DIR")
def _get_enabled_extensions(): std_out, _, _ = _execute( 'gsettings get org.gnome.shell enabled-extensions') try: return ast.literal_eval(std_out) except: return [] ext = ['user', 'system', 'all'] ext.extend(_get_extensions('all')) extension_decorator = argh.arg( 'extensions', nargs="+", choices=ext, metavar='', help="run the list-extensions command to see a list of available" " extensions") def _expand_requested_extension_list(extensions): default_extensions = _current_extensions() final_extension_list = [] for location in ['user', 'system', 'all']: if location in extensions: try: while True: extensions.remove(location) except: pass
def arg_target_nodes_0_to_n(method): b = argh.arg('nodes', type=str, help='target nodes (regexp)', nargs="?") return arg_exclude_nodes(b(method))
""" Creates a single decorator that applies multiple argh.arg decorators for commands with a common set of arguments. Args: *arg_defs (list): List of decorators to apply """ def decorator(fn): for arg_def in arg_defs: arg_def(fn) return fn return decorator sql_args = arg_group( argh.arg('--sql-host', default='localhost', help='hostname of the SQL server'), argh.arg('--sql-user', default='root', help='username used to log in to the SQL server'), argh.arg('--sql-password', default='password', help="password used to log in to the SQL server")) def has_whitespace(string): return any(ch.isspace() for ch in string) class VerifyNoWhiteSpace(argparse.Action): """ Ensures that a command line argument does not contain whitespace. Exits with a warning
print '\n'.join(extensions) def _get_enabled_extensions(): std_out, _, _ = _execute( 'gsettings get org.gnome.shell enabled-extensions') try: return ast.literal_eval(std_out) except: return [] ext = ['user', 'system', 'all'] ext.extend(_get_extensions('all')) extension_decorator = argh.arg( 'extensions', nargs="+", choices=ext, metavar='', help="run the list-extensions command to see a list of available" " extensions") def _expand_requested_extension_list(extensions): default_extensions = _current_extensions() final_extension_list = [] for location in ['user', 'system', 'all']: if location in extensions: try: while True: extensions.remove(location) except: pass final_extension_list.extend(default_extensions[location]) final_extension_list.extend(extensions)
def inner(f: Callable) -> Callable: for decorator in reversed(decorators): f = decorator(f) return f return inner # Define a common set of command line options. # For instance, almost every command has a # `-w,--workspace` option, which is defined here. workspace_arg = arg( "-w", "--workspace", dest="workspace_path", help="path to the current workspace", type=Path, ) groups_arg = arg( "-g", "--group", "--groups", nargs="+", dest="groups", help="groups to use" ) all_cloned_arg = arg( "--all-cloned", action="store_true", dest="all_cloned", help="run on all cloned repos", ) def repos_arg(f: Callable) -> Callable:
""" import datetime, os from requests.exceptions import HTTPError, ConnectionError, InvalidSchema from argh import arg, ArghParser from argh.exceptions import CommandError from gestus_client import logging_handler from gestus_client import __version__ as client_version from gestus_client.config import GestusConfig from gestus_client.client import GestusClient, WebsitePostException, ENVIRONMENT_KIND_CHOICES, ENVIRONMENT_KIND_KEYS # Available common options for all commands cmd_user_opt = arg("-u", "--user", default=None, help="Username to connect to the service") cmd_password_opt = arg("-p", "--password", default=None, help="Password to connect to the service") cmd_host_opt = arg("-o", "--host", default=None, help="Http(s) address to connect to the service") cmd_config_opt = arg("-c", "--config", default="gestus.cfg", help="Path to the client config file") cmd_passive_opt = arg("--passive", default=False, action="store_true", help="Disable config saving") cmd_loglevel_opt = arg( "-l", "--loglevel", default="info", choices=["debug", "info", "warning", "error", "critical"], help="The minimal verbosity level to limit logs output", ) cmd_logfile_opt = arg("--logfile", default=None, help="A filepath that if setted, will be used to save logs output") cmd_timer_opt = arg( "-t", "--timer", default=False, action="store_true", help="Display elapsed time at the end of execution" )
"""Export a Spotify playlist to CSV""" import csv import re import spotipy import sys import io from argh import arg, named, CommandError from .config import read_config from .spotipyutil import prompt_for_user_token SPOTIFY_API_SCOPE = 'user-library-read' USERNAME_ARG = arg('--username', help='Your Spotify user name', default=read_config().get("Spotify", "username")) CLIENT_ID_ARG = arg('--client-id', default=read_config().get("Spotify", "client-id")) CLIENT_SECRET_ARG = arg('--client-secret', default=read_config().get("Spotify", "client-secret")) REDIRECT_URI_ARG = arg('--redirect-uri', default=read_config().get("Spotify", "redirect-uri")) @arg('tracklist', help="A text file containing the Spotify track URIs.") @named('export-tracks') def exporttracks(tracklist): """ Given a list of Spotify track URIs, prints the track Title, Artist and Album.