Python clint.textui.indent() Examples
The following are 30
code examples of clint.textui.indent().
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
clint.textui
, or try the search function
.
Example #1
Source File: app_processes.py From commcare-cloud with BSD 3-Clause "New" or "Revised" License | 6 votes |
def filter_out_deprecated_pillows(environment, pillows): deprecated_pillows = ['GeographyFluffPillow', 'FarmerRecordFluffPillow'] good_pillows = {} bad_pillows = set() for host, pillow_configs in pillows.items(): good_pillows[host] = {} for pillow_name, pillow_config in pillow_configs.items(): if pillow_name not in deprecated_pillows: good_pillows[host][pillow_name] = pillow_config else: bad_pillows.add(pillow_name) if bad_pillows: puts(color_warning( 'This environment references deprecated pillow(s):\n' )) with indent(): for pillow_name in sorted(bad_pillows): puts(color_warning('- {}'.format(pillow_name))) puts(color_warning( '\nThis pillows are unused and no longer needed.\n' 'To get rid of this warning, remove those pillows from {}' .format(environment.paths.app_processes_yml) )) return good_pillows
Example #2
Source File: user.py From indras_net with GNU General Public License v3.0 | 6 votes |
def tell(msg, type=INFO, indnt=0, utype=TERMINAL, text_output=None, reverse=True): if utype == WEB: if reverse: return msg + "\n" + text_output else: return text_output + "\n" + msg else: if indnt <= 0: if clint_present: puts(text_colors[type](msg)) else: print(msg) else: if clint_present: with indent(indnt): puts(text_colors[type](msg)) else: for i in range(0, indnt): msg = ' ' + msg print(msg)
Example #3
Source File: core.py From slack-machine with MIT License | 6 votes |
def load_plugins(self): with indent(4): logger.debug("PLUGINS: %s", self._settings['PLUGINS']) for plugin in self._settings['PLUGINS']: for class_name, cls in import_string(plugin): if issubclass(cls, MachineBasePlugin) and cls is not MachineBasePlugin: logger.debug("Found a Machine plugin: {}".format(plugin)) storage = PluginStorage(class_name) instance = cls(SlackClient(), self._settings, storage) missing_settings = self._register_plugin(class_name, instance) if missing_settings: show_invalid(class_name) with indent(4): error_msg = "The following settings are missing: {}".format( ", ".join(missing_settings) ) puts(colored.red(error_msg)) puts(colored.red("This plugin will not be loaded!")) del instance else: instance.init() show_valid(class_name) self._storage.set('manual', dill.dumps(self._help))
Example #4
Source File: stop.py From pgrepup with GNU General Public License v3.0 | 6 votes |
def stop(): # Shortcut to ask master password before output Configuration message decrypt(config().get('Source', 'password')) output_cli_message("Check active subscriptions in Destination nodes", color='cyan') puts("") subscriptions = get_destination_subscriptions() with indent(4, quote=' >'): for s in iter(subscriptions.keys()): output_cli_message(s) message = colored.yellow("Active") if subscriptions[s] else colored.green("Stopped") print(output_cli_result(message)) if subscriptions[s]: with indent(4, quote=' '): output_cli_message("Launch stop command") syncronize_sequences(s) # must be done BEFORE stopping subscriptions print(output_cli_result(stop_subscription(s), 8))
Example #5
Source File: ops_tool.py From commcare-cloud with BSD 3-Clause "New" or "Revised" License | 6 votes |
def run(self, args, unknown_args): environment = get_environment(args.env_name) couch_config = get_couch_config(environment) puts(u'\nMembership') with indent(): puts(get_membership(couch_config).get_printable()) puts(u'\nDB Info') print_db_info(couch_config) puts(u'\nShard allocation') print_shard_table([ get_shard_allocation(couch_config, db_name) for db_name in sorted(get_db_list(couch_config.get_control_node())) ]) return 0
Example #6
Source File: reference.py From VCF-kit with MIT License | 6 votes |
def resolve_reference_genome(loc): """ Resolve location of reference genome file. """ if loc is None: message("You must specify a genome:") output_genome_list() exit() if os.path.exists(loc): return loc else: if loc in get_genome_list(): reference_location = "{gd}/{loc}/{loc}.fa.gz".format(gd = get_genome_directory(), loc = loc) with indent(4): puts_err(colored.green("\nUsing reference located at %s\n" % reference_location)) return reference_location else: with indent(4): exit(puts_err(colored.red("\nGenome '%s' does not exist\n" % loc)))
Example #7
Source File: i18ntool.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def update(user, password, lang=None): langs = getlangs(lang) puts(u"Updating %s" % ', '.join(langs)) for loc in langs: with indent(2): puts(u"Downloading PO for %s" % loc) url = (u'https://www.transifex.com/projects/p/formhub/' u'resource/django/l/%(lang)s/download/for_use/' % {'lang': loc}) try: tmp_po_file = download_with_login(url, TX_LOGIN_URL, login=user, password=password, ext='po', username_field='identification', password_field='password', form_id=1) po_file = os.path.join(REPO_ROOT, 'locale', loc, 'LC_MESSAGES', 'django.po') with indent(2): puts(u"Copying downloaded file to %s" % po_file) shutil.move(tmp_po_file, po_file) except Exception as e: puts(colored.red(u"Unable to update %s " u"from Transifex: %r" % (loc, e))) puts(colored.green("sucesssfuly retrieved %s" % loc)) compile_mo(langs)
Example #8
Source File: couchdb.py From commcare-cloud with BSD 3-Clause "New" or "Revised" License | 6 votes |
def describe(migration): puts(u'\nMembership') with indent(): puts(get_membership(migration.target_couch_config).get_printable()) puts(u'\nDB Info') print_db_info(migration.target_couch_config) puts(u'\nShard allocation') diff_with_db = diff_plan(migration) if diff_with_db: puts(color_highlight('DB allocation differs from plan:\n')) puts("{}\n\n".format(diff_with_db)) else: puts(color_success('DB allocation matches plan.')) print_shard_table([ get_shard_allocation(migration.target_couch_config, db_name) for db_name in sorted(get_db_list(migration.target_couch_config.get_control_node())) ]) return 0
Example #9
Source File: i18ntool.py From kobo-predict with BSD 2-Clause "Simplified" License | 6 votes |
def usage(exit=True, code=1): print(u"i18n wrapper script for formhub.\n") with indent(4): puts(colored.yellow(u",/i18ntool.py add --lang <lang>")) puts(u"Create required files for enabling translation " u"of language with code <lang>\n") puts(colored.yellow(u"./i18ntool.py refresh [--lang <lang>]")) puts(u"Update the PO file for <lang> based on code.\n" u"<lang> is optionnal as we only use EN and do " u"all translations in Transifex.\n") puts(colored.yellow(u"./i18ntool.py update --user <tx_user> " u"--password <tx_pass> [--lang <lang>]")) puts(u"Downloads new PO files for <lang> (or all) from Transifex " u"then compiles new MO files\n") puts(colored.yellow(u"./i18ntool.py compile [--lang <lang>]")) puts(u"Compiles all PO files for <lang> (or all) into MO files.\n" u"Not required unless you want to.\n") if exit: sys.exit(code)
Example #10
Source File: cl_utils.py From bcwallet with Apache License 2.0 | 6 votes |
def txn_preference_chooser(user_prompt=DEFAULT_PROMPT): puts('How quickly do you want this transaction to confirm? The higher the miner preference, the higher the transaction fee.') TXN_PREFERENCES = ( ('high', '1-2 blocks to confirm'), ('medium', '3-6 blocks to confirm'), ('low', '7+ blocks to confirm'), # ('zero', 'no fee, may not ever confirm (advanced users only)'), ) for cnt, pref_desc in enumerate(TXN_PREFERENCES): pref, desc = pref_desc with indent(2): puts(colored.cyan('%s (%s priority): %s' % (cnt+1, pref, desc))) choice_int = choice_prompt( user_prompt=user_prompt, acceptable_responses=range(1, len(TXN_PREFERENCES)+1), default_input='1', # high pref show_default=True, ) return TXN_PREFERENCES[int(choice_int)-1][0]
Example #11
Source File: couchdb.py From commcare-cloud with BSD 3-Clause "New" or "Revised" License | 6 votes |
def assert_files(migration, alloc_docs_by_db, ansible_context): files_by_node = get_files_for_assertion(alloc_docs_by_db) expected_files_vars = os.path.abspath(os.path.join(migration.working_dir, 'assert_vars.yml')) with open(expected_files_vars, 'w') as f: yaml.safe_dump({ 'files_by_node': files_by_node, 'couch_data_dir': migration.couchdb2_data_dir, }, f, indent=2) play_path = os.path.join(PLAY_DIR, 'assert_couch_files.yml') return_code = run_ansible_playbook( migration.target_environment, play_path, ansible_context, always_skip_check=True, quiet=True, unknown_args=['-e', '@{}'.format(expected_files_vars)] ) return return_code == 0
Example #12
Source File: call.py From VCF-kit with MIT License | 6 votes |
def seq_type(filename): """ Resolves sequence filetype using extension. """ filename, ext = os.path.splitext(filename.lower()) if ext in [".fasta", ".fa"]: extension = 'fasta' elif ext in [".fastq",".fq"]: extension = 'fastq' elif ext in [".ab1", '.abi']: extension = 'abi' else: raise Exception("Unknown sequence file type: " + filename) with indent(4): puts_err(colored.green("\nReading sequences as %s\n" % extension.upper())) return extension
Example #13
Source File: cli.py From pychievements with MIT License | 6 votes |
def print_goals(achievement_or_iter, indent=2): """ Displays all of the available goals registered for the given achievement(s) """ from clint.textui import puts from clint.textui.cols import console_width from clint.textui import indent as _indent if _isclass(achievement_or_iter) and issubclass(achievement_or_iter, Achievement): achievement_or_iter = [achievement_or_iter] for achievement in achievement_or_iter: with _indent(indent): puts("{0}\n{1}\n".format(achievement.name, '='*(console_width({})-indent-2))) for goal in achievement.goals: print_goal(goal, True, indent=indent) puts("\n")
Example #14
Source File: cli.py From pychievements with MIT License | 6 votes |
def print_goal(goal, achieved=False, level=None, indent=2): """ Print a goals description with its icon. Achieved (True/False) will choose the correct icon from the goal. If a level is specified, a tracker line will be added under the icon showing the current level out of the required level for the goal. If level is > the required level, achieved will be set to true. """ from clint.textui import puts from clint.textui import indent as _indent from clint.textui.cols import columns, console_width if level is not None and level >= goal['level']: achieved = True icon = (goal['icon'].achieved() if achieved else goal['icon'].unachieved()).split('\n') maxiw = max([len(str(_)) for _ in icon]) descw = console_width({})-maxiw-(indent + 4) desc = '{0}\n{1}\n\n{2}'.format(goal['name'], '-'*len(goal['name']), columns([goal['description'], descw])).split('\n') if level is not None: if level > goal['level']: level = goal['level'] maxitw = max([len(_) for _ in icon]) icon.append(("%d/%d" % (level, goal['level'])).center(maxitw)) with _indent(indent): for i, d in _zip_longest(icon, desc): puts("{1:{0}} {2}".format(maxiw, str(i) if i is not None else "", d.strip() if d is not None else ""))
Example #15
Source File: cl_utils.py From bcwallet with Apache License 2.0 | 5 votes |
def debug_print(to_print): if type(to_print) is dict: to_print = json.dumps(to_print, cls=DateTimeEncoder, indent=2) puts(colored.yellow(str(to_print)))
Example #16
Source File: __init__.py From VCF-kit with MIT License | 5 votes |
def message(message, n_indent = 4, color = "blue"): with indent(n_indent): if color == "blue": puts_err(colored.blue('\n' + message + '\n')) elif color == "red": puts_err(colored.blue('\n' + message + '\n'))
Example #17
Source File: genome.py From VCF-kit with MIT License | 5 votes |
def download_genomes(genome_db): if os.path.isfile(genome_db): fileTime = os.path.getmtime(genome_db) else: fileTime = 0 if (time() - fileTime) > (3 * 30 * 24 * 60 * 60) or is_non_zero_file(genome_db) is False: with indent(2): puts(colored.blue('\nDownloading list of reference genomes\n')) r = requests.get("http://ftp.ncbi.nlm.nih.gov/genomes/ASSEMBLY_REPORTS/assembly_summary_refseq.txt") genome_file = open(genome_db, "w") with genome_file as f: f.write(r.text.encode('utf-8').strip())
Example #18
Source File: core.py From slack-machine with MIT License | 5 votes |
def __init__(self, settings=None): announce("Initializing Slack Machine:") with indent(4): puts("Loading settings...") if settings: self._settings = settings found_local_settings = True else: self._settings, found_local_settings = import_settings() fmt = '[%(asctime)s][%(levelname)s] %(name)s %(filename)s:%(funcName)s:%(lineno)d |' \ ' %(message)s' date_fmt = '%Y-%m-%d %H:%M:%S' log_level = self._settings.get('LOGLEVEL', logging.ERROR) logging.basicConfig( level=log_level, format=fmt, datefmt=date_fmt, ) if not found_local_settings: warn("No local_settings found! Are you sure this is what you want?") if 'SLACK_API_TOKEN' not in self._settings: error("No SLACK_API_TOKEN found in settings! I need that to work...") sys.exit(1) self._client = LowLevelSlackClient() puts("Initializing storage using backend: {}".format(self._settings['STORAGE_BACKEND'])) self._storage = Storage.get_instance() logger.debug("Storage initialized!") self._plugin_actions = { 'listen_to': {}, 'respond_to': {} } self._help = { 'human': {}, 'robot': {} } self._dispatcher = EventDispatcher(self._plugin_actions, self._settings) puts("Loading plugins...") self.load_plugins() logger.debug("The following plugin actions were registered: %s", self._plugin_actions)
Example #19
Source File: bcwallet.py From bcwallet with Apache License 2.0 | 5 votes |
def dump_private_keys_or_addrs_chooser(wallet_obj): ''' Offline-enabled mechanism to dump everything ''' if wallet_obj.private_key: puts('Which private keys and addresses do you want?') else: puts('Which addresses do you want?') with indent(2): puts(colored.cyan('1: Active - have funds to spend')) puts(colored.cyan('2: Spent - no funds to spend (because they have been spent)')) puts(colored.cyan('3: Unused - no funds to spend (because the address has never been used)')) puts(colored.cyan('0: All (works offline) - regardless of whether they have funds to spend (super advanced users only)')) puts(colored.cyan('\nb: Go Back\n')) choice = choice_prompt( user_prompt=DEFAULT_PROMPT, acceptable_responses=[0, 1, 2, 3], default_input='1', show_default=True, quit_ok=True, ) if choice is False: return if choice == '1': return dump_selected_keys_or_addrs(wallet_obj=wallet_obj, zero_balance=False, used=True) elif choice == '2': return dump_selected_keys_or_addrs(wallet_obj=wallet_obj, zero_balance=True, used=True) elif choice == '3': return dump_selected_keys_or_addrs(wallet_obj=wallet_obj, zero_balance=None, used=False) elif choice == '0': return dump_all_keys_or_addrs(wallet_obj=wallet_obj)
Example #20
Source File: cl_utils.py From bcwallet with Apache License 2.0 | 5 votes |
def coin_symbol_chooser(user_prompt=DEFAULT_PROMPT, quit_ok=True): ACTIVE_COIN_SYMBOL_LIST = [x for x in COIN_SYMBOL_LIST if x != 'uro'] for cnt, coin_symbol_choice in enumerate(ACTIVE_COIN_SYMBOL_LIST): with indent(2): puts(colored.cyan('%s: %s' % ( cnt+1, COIN_SYMBOL_MAPPINGS[coin_symbol_choice]['display_name'], ))) if ACTIVE_COIN_SYMBOL_LIST[4] == 'bcy': default_input = 5 show_default = True else: default_input = None show_default = False coin_symbol_int = get_int( min_int=1, user_prompt=user_prompt, max_int=len(ACTIVE_COIN_SYMBOL_LIST), default_input=default_input, show_default=show_default, quit_ok=quit_ok, ) if not coin_symbol_int: return False else: return ACTIVE_COIN_SYMBOL_LIST[coin_symbol_int-1]
Example #21
Source File: cl_utils.py From bcwallet with Apache License 2.0 | 5 votes |
def print_bcwallet_basic_pub_opening(mpub): puts("You've opened your HD wallet in PRIVATE key mode, so you CAN sign transactions.") puts("If you like, you can always open your HD wallet in PUBLIC key mode like this:\n") with indent(2): puts(colored.magenta('$ bcwallet --wallet=%s\n' % mpub))
Example #22
Source File: cl_utils.py From bcwallet with Apache License 2.0 | 5 votes |
def print_bcwallet_basic_priv_opening(priv_to_display): with indent(4): puts(colored.magenta('$ bcwallet --wallet=%s\n' % priv_to_display))
Example #23
Source File: cl_utils.py From bcwallet with Apache License 2.0 | 5 votes |
def print_bcwallet_piped_priv_cat_opening(): with indent(4): puts(colored.magenta('$ cat wallet_seed.txt | bcwallet\n'))
Example #24
Source File: bcwallet.py From bcwallet with Apache License 2.0 | 5 votes |
def send_chooser(wallet_obj): puts('What do you want to do?:') if not USER_ONLINE: puts("(since you are NOT connected to BlockCypher, many choices are disabled)") with indent(2): puts(colored.cyan('1: Basic send (generate transaction, sign, & broadcast)')) puts(colored.cyan('2: Sweep funds into bcwallet from a private key you hold')) puts(colored.cyan('3: Offline transaction signing (more here)')) puts(colored.cyan('\nb: Go Back\n')) choice = choice_prompt( user_prompt=DEFAULT_PROMPT, acceptable_responses=range(0, 5+1), quit_ok=True, default_input='1', show_default=True, ) verbose_print('Choice: %s' % choice) if choice is False: return elif choice == '1': return send_funds(wallet_obj=wallet_obj) elif choice == '2': return sweep_funds_from_privkey(wallet_obj=wallet_obj) elif choice == '3': offline_tx_chooser(wallet_obj=wallet_obj)
Example #25
Source File: bcwallet.py From bcwallet with Apache License 2.0 | 5 votes |
def print_path_info(address, path, coin_symbol, wif=None): assert path, path assert coin_symbol, coin_symbol assert address, address if wif: address_formatted = '%s/%s' % (address, wif) else: address_formatted = address if USER_ONLINE: addr_balance = get_total_balance( address=address, coin_symbol=coin_symbol, ) with indent(2): puts(colored.green('%s (%s) - %s' % ( path, address_formatted, format_crypto_units( input_quantity=addr_balance, input_type='satoshi', output_type=UNIT_CHOICE, coin_symbol=coin_symbol, print_cs=True, ), ))) else: with indent(2): puts(colored.green('%s (%s)' % ( path, address_formatted, )))
Example #26
Source File: datadog_monitors.py From commcare-cloud with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _print_monitors(api, title, monitors, show_filenames, sort_index): if not monitors: return puts(title) with indent(): output_list = sorted([ (id, _get_display(api, monitor, show_filenames)) for id, monitor in monitors.items() ], key=lambda p: p[sort_index]) for id, name in output_list: puts("{:<10}: {}".format(id, name))
Example #27
Source File: downtime.py From commcare-cloud with BSD 3-Clause "New" or "Revised" License | 5 votes |
def start_downtime(environment, ansible_context, args): downtime = get_downtime_record(environment) if downtime: puts(color_notice('Downtime already active')) with indent(): print_downtime(downtime) go_down = ask("Do you want to continue?") else: go_down = ask("Are you sure you want to stop all CommCare services?", strict=True) if go_down: if not downtime: create_downtime_record(environment, args.message, args.duration) supervisor_services(environment, ansible_context, 'stop') wait_for_all_processes_to_stop(environment, ansible_context)
Example #28
Source File: couchdb.py From commcare-cloud with BSD 3-Clause "New" or "Revised" License | 5 votes |
def generate_shard_plan(migration): shard_allocations = generate_shard_allocation( migration.source_couch_config, migration.plan.target_allocation ) with open(migration.shard_plan_path, 'w') as f: plan = { shard_allocation_doc.db_name: shard_allocation_doc.to_plan_json() for shard_allocation_doc in shard_allocations } # hack - yaml didn't want to dump this directly yaml.safe_dump(json.loads(json.dumps(plan)), f, indent=2) return shard_allocations
Example #29
Source File: core.py From slack-machine with MIT License | 5 votes |
def run(self): announce("\nStarting Slack Machine:") with indent(4): show_valid("Connected to Slack") Scheduler.get_instance().start() show_valid("Scheduler started") if not self._settings['DISABLE_HTTP']: self._bottle_thread = Thread( target=bottle.run, kwargs=dict( host=self._settings['HTTP_SERVER_HOST'], port=self._settings['HTTP_SERVER_PORT'], server=self._settings['HTTP_SERVER_BACKEND'], ) ) self._bottle_thread.daemon = True self._bottle_thread.start() show_valid("Web server started") if self._settings['KEEP_ALIVE']: self._keep_alive_thread = Thread(target=self._keepalive) self._keep_alive_thread.daemon = True self._keep_alive_thread.start() show_valid( "Keepalive thread started [Interval: %ss]" % self._settings['KEEP_ALIVE'] ) show_valid("Dispatcher started") self._dispatcher.start()
Example #30
Source File: version.py From orbital with MIT License | 5 votes |
def release(): """Bump version, tag, build, gen docs.""" if check_staged(): raise EnvironmentError('There are staged changes, abort.') if check_unstaged(): raise EnvironmentError('There are unstaged changes, abort.') bump() tag() build() doc_gen() puts(colored.yellow("Remember to upload documentation and package:")) with indent(2): puts(colored.cyan("shovel doc.upload")) puts(colored.cyan("shovel version.upload"))