class CommandCompleter(Completer): """ Completer for command names. """ def __init__(self): # Completer for full command names. self._command_completer = WordCompleter( sorted(COMMANDS_TO_HANDLERS.keys()), ignore_case=True, WORD=True, match_middle=True) # Completer for aliases. self._aliases_completer = WordCompleter( sorted(ALIASES.keys()), ignore_case=True, WORD=True, match_middle=True) def get_completions(self, document, complete_event): # First, complete on full command names. found = False for c in self._command_completer.get_completions(document, complete_event): found = True yield c # When no matches are found, complete aliases instead. # The completion however, inserts the full name. if not found: for c in self._aliases_completer.get_completions(document, complete_event): full_name = ALIASES.get(c.display) yield Completion(full_name, start_position=c.start_position, display='%s (%s)' % (c.display, full_name))
def test_word_completer_ignore_case(): completer = WordCompleter(['abc', 'def', 'aaa'], ignore_case=True) completions = completer.get_completions(Document('a'), CompleteEvent()) assert [c.text for c in completions] == ['abc', 'aaa'] completions = completer.get_completions(Document('A'), CompleteEvent()) assert [c.text for c in completions] == ['abc', 'aaa']
def test_word_completer_sentence(): # With sentence=True completer = WordCompleter(['hello world', 'www', 'hello www', 'hello there'], sentence=True) completions = completer.get_completions(Document('hello w'), CompleteEvent()) assert [c.text for c in completions] == ['hello world', 'hello www'] # With sentence=False completer = WordCompleter(['hello world', 'www', 'hello www', 'hello there'], sentence=False) completions = completer.get_completions(Document('hello w'), CompleteEvent()) assert [c.text for c in completions] == ['www']
def __init__(self): # Completer for full command names. self._command_completer = WordCompleter( sorted(COMMANDS_TO_HANDLERS.keys()), ignore_case=True, WORD=True, match_middle=True) # Completer for aliases. self._aliases_completer = WordCompleter( sorted(ALIASES.keys()), ignore_case=True, WORD=True, match_middle=True)
def test_word_completer_pattern(): # With a pattern which support '.' completer = WordCompleter(['abc', 'a.b.c', 'a.b', 'xyz'], pattern=re.compile(r'^([a-zA-Z0-9_.]+|[^a-zA-Z0-9_.\s]+)')) completions = completer.get_completions(Document('a.'), CompleteEvent()) assert [c.text for c in completions] == ['a.b.c', 'a.b'] # Without pattern completer = WordCompleter(['abc', 'a.b.c', 'a.b', 'xyz']) completions = completer.get_completions(Document('a.'), CompleteEvent()) assert [c.text for c in completions] == []
def get_completions_for_parts(parts, last_part, complete_event, pymux): completer = None # Resolve aliases. if len(parts) > 0: parts = [ALIASES.get(parts[0], parts[0])] + parts[1:] if len(parts) == 0: # New command. completer = _command_completer elif len(parts) >= 1 and last_part.startswith('-'): flags = get_option_flags_for_command(parts[0]) completer = WordCompleter(sorted(flags), WORD=True) elif len(parts) == 1 and parts[0] in ('set-option', 'set-window-option'): options = pymux.options if parts[0] == 'set-option' else pymux.window_options completer = WordCompleter(sorted(options.keys()), sentence=True) elif len(parts) == 2 and parts[0] in ('set-option', 'set-window-option'): options = pymux.options if parts[0] == 'set-option' else pymux.window_options option = options.get(parts[1]) if option: completer = WordCompleter(sorted(option.get_all_values(pymux)), sentence=True) elif len(parts) == 1 and parts[0] == 'select-layout': completer = _layout_type_completer elif len(parts) == 1 and parts[0] == 'send-keys': completer = _keys_completer elif parts[0] == 'bind-key': if len(parts) == 1: completer = _keys_completer elif len(parts) == 2: completer = _command_completer # Recursive, for bind-key options. if parts and parts[0] == 'bind-key' and len(parts) > 2: for c in get_completions_for_parts(parts[2:], last_part, complete_event, pymux): yield c if completer: for c in completer.get_completions(Document(last_part), complete_event): yield c
def test_word_completer_static_word_list(): completer = WordCompleter(['abc', 'def', 'aaa']) # Static list on empty input. completions = completer.get_completions(Document(''), CompleteEvent()) assert [c.text for c in completions] == ['abc', 'def', 'aaa'] # Static list on non-empty input. completions = completer.get_completions(Document('a'), CompleteEvent()) assert [c.text for c in completions] == ['abc', 'aaa'] completions = completer.get_completions(Document('A'), CompleteEvent()) assert [c.text for c in completions] == [] # Multiple words. (Check last only.) completions = completer.get_completions(Document('test a'), CompleteEvent()) assert [c.text for c in completions] == ['abc', 'aaa']
def test_word_completer_dynamic_word_list(): called = [0] def get_words(): called[0] += 1 return ['abc', 'def', 'aaa'] completer = WordCompleter(get_words) # Dynamic list on empty input. completions = completer.get_completions(Document(''), CompleteEvent()) assert [c.text for c in completions] == ['abc', 'def', 'aaa'] assert called[0] == 1 # Static list on non-empty input. completions = completer.get_completions(Document('a'), CompleteEvent()) assert [c.text for c in completions] == ['abc', 'aaa'] assert called[0] == 2
def test_word_completer_match_middle(): completer = WordCompleter(['abc', 'def', 'abca'], match_middle=True) completions = completer.get_completions(Document('bc'), CompleteEvent()) assert [c.text for c in completions] == ['abc', 'abca']
# Example: Rule-based chatbots(Also Noob) import re import random from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import WordCompleter ElizaCompleter = WordCompleter( ["do you think ", "do you remember ", "I want ", "if "], sentence=True, match_middle=True, ) bot_template = "BOT : {0}" # A dictionary of questions, patterns as keys and # lists of appropriate responses as values rules = { "I want (.*)": [ "What would it mean if you got {0}", "Why do you want {0}", "What's stopping you from getting {0}", ], "do you remember (.*)": [ "Did you think I would forget {0}", "Why haven't you been able to forget {0}", "What about {0}", "Yes .. and?", ],
def _get_completer(self): return WordCompleter([])
def __init__(self, hummingbot_application): super(HummingbotCompleter, self).__init__() self.hummingbot_application = hummingbot_application self._path_completer = WordCompleter( file_name_list(CONF_FILE_PATH, "yml")) self._command_completer = WordCompleter(self.parser.commands, ignore_case=True) self._exchange_completer = WordCompleter(EXCHANGES, ignore_case=True) self._connect_exchange_completer = WordCompleter(CONNECT_EXCHANGES, ignore_case=True) self._export_completer = WordCompleter(["keys", "trades"], ignore_case=True) self._strategy_completer = WordCompleter(STRATEGIES, ignore_case=True)
def _config_completer(self): return WordCompleter(load_required_configs(), ignore_case=True)
# Definitions of commands CMD_HELP = "help" CMD_LOAD = "load" CMD_REGISTERS = "registers" CMD_FIND = "find" CMD_PAYLOAD = "payload" CMD_CONTEXT = "context" CMD_CONFIG = "config" CMD_EXPLOIT = "exploit" CMD_EXIT = "exit" command_list = [ CMD_HELP, CMD_LOAD, CMD_REGISTERS, CMD_FIND, CMD_CONFIG, CMD_EXIT ] command_completer = WordCompleter(command_list) command_history = InMemoryHistory() def main(time_mesure=False): if (time_mesure): pr = cProfile.Profile() pr.enable() style = Style.from_dict({ 'prompt': '#00FF00', }) message = [ (u'class:prompt', u'>>> '),
Version: 1.0 ''' import os, sys from datetime import datetime from rich.console import Console from rich.table import Table from prompt_toolkit import PromptSession from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit import prompt from prompt_toolkit.styles import Style from prompt_toolkit.formatted_text import HTML from prompt_toolkit.completion import WordCompleter ######################### global ######################## WordAdb = WordCompleter([ '?', 'help', 'update', 'clear', 'exit', 'shodan init ', 'shodan search ', 'connect ', 'tcpip', 'show apikey', 'show devices', 'exploit' ]) WordExp = WordCompleter([ '?', 'help', 'clear', 'back', 'app', 'shell', 'sysinfo', 'screencap', 'screenrec', 'usekey', 'download', 'root', 'reboot' ]) KeyList = ('UNKOWN', 'MENU', 'SOFT_RIGHT', 'HOME', 'BACK', 'ENDCALL', 'CALL', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'START', 'POUND', 'DPAD_UP', 'DPAD_DOWN', 'DPAD_LEFT', 'DPAD_RIGHT', 'DPAD_CENTER', 'VOLUME_UP', 'VOLUME_DOWN', 'POWER', 'CAMERA', 'CLEAR', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'COMMA', 'PERIOD', 'ALT_LEFT', 'ALT_RIGHT', 'SHIFT_LEFT', 'SHIFT_RIGHT', 'TAB', 'SPACE', 'SYM', 'EXPLORER', 'ENVELOPE', 'ENTER', 'DELETE', 'GRAVE', 'MINUS', 'EQUALS', 'LEFT_BRACKET', 'RIGHT_BRACKET', 'BACKSLASH', 'SEMICOLON', 'APOSTROPHE', 'SLASH', 'AT', 'NUM',
def _wallet_address_completer(self): return WordCompleter(list_wallets(), ignore_case=True)
def get_completions(self, document: Document, complete_event: CompleteEvent) -> Iterable[Completion]: """ Get a list of completions for the given document """ text = document.text_before_cursor.lstrip() try: args = shlex.split(text) except ValueError: try: args = shlex.split(text + '"') except ValueError: args = shlex.split(text + "'") # We haven't finished typing the command. Use our word completer for # commands if text == "" or (len(args) == 1 and not text.endswith(" ")): yield from self.completer.get_completions(document, complete_event) return # Not in a known command, can't autocomplete if args[0] not in self.layers: return command = self.layers[args[0]] args = args[1:] next_completer = command[0] this_completer = command[0] positional = 0 # state = "options", completing options next # state = "arguments", completing arguments to options next state = "options" for arg in args: if state == "options": # Flag options if arg.startswith("-"): # Exact match, with a sub-completer if arg in command[2] and command[2][arg] is not None: # Completer for next argument next_completer = command[2][arg] state = "arguments" # Exact match, with no arguments elif arg in command[2]: # Command has no argument, next completer is options # completer next_completer = command[0] state = "options" this_completer = command[0] # Non-exact match else: next_completer = command[0] this_completer = command[0] state = "options" # Appears to be a positional argument, grab next positional # completer and increment positional count else: if positional < len(command[1]): this_completer = command[1][positional] next_completer = command[0] state = "options" positional += 1 else: this_completer = command[0] next_completer = command[0] state = "options" else: # Completing an argument to a option/switch. We can't verify # it's legitimacy, so we assume it's right, and reset to a # default state. state = "options" this_completer = next_completer next_completer = command[0] if isinstance(this_completer, tuple) and this_completer[0] == "choices": this_completer = WordCompleter(this_completer[1]) if isinstance(next_completer, tuple) and next_completer[0] == "choices": next_completer = WordCompleter(next_completer[1]) if text.endswith(" ") and next_completer is not None: yield from next_completer.get_completions(document, complete_event) elif this_completer is not None: yield from this_completer.get_completions(document, complete_event)
class CommandCompleter(Completer): """ Complete commands from a given list of commands """ def __init__(self, commands: List["CommandDefinition"]): """ Construct a new command completer """ self.layers = {} local_file_completer = LocalPathCompleter() remote_file_completer = RemotePathCompleter() for command in commands: self.layers[command.PROG] = [None, [], {}] option_names = [] for name_list, descr in command.ARGS.items(): name_list = name_list.split(",") if descr[0] == Complete.CHOICES: completer = WordCompleter(descr[3]["choices"]) elif descr[0] == Complete.LOCAL_FILE: completer = local_file_completer elif descr[0] == Complete.REMOTE_FILE: completer = remote_file_completer elif descr[0] == Complete.NONE: completer = None if len(name_list) == 1 and not name_list[0].startswith("-"): self.layers[command.PROG][1].append(completer) else: for name in name_list: self.layers[command.PROG][2][name] = completer option_names.append(name) self.layers[command.PROG][0] = WordCompleter(option_names + ["--help", "-h"]) self.completer = WordCompleter(list(self.layers)) def get_completions(self, document: Document, complete_event: CompleteEvent) -> Iterable[Completion]: """ Get a list of completions for the given document """ text = document.text_before_cursor.lstrip() try: args = shlex.split(text) except ValueError: try: args = shlex.split(text + '"') except ValueError: args = shlex.split(text + "'") # We haven't finished typing the command. Use our word completer for # commands if text == "" or (len(args) == 1 and not text.endswith(" ")): yield from self.completer.get_completions(document, complete_event) return # Not in a known command, can't autocomplete if args[0] not in self.layers: return command = self.layers[args[0]] args = args[1:] next_completer = command[0] this_completer = command[0] positional = 0 # state = "options", completing options next # state = "arguments", completing arguments to options next state = "options" for arg in args: if state == "options": # Flag options if arg.startswith("-"): # Exact match, with a sub-completer if arg in command[2] and command[2][arg] is not None: # Completer for next argument next_completer = command[2][arg] state = "arguments" # Exact match, with no arguments elif arg in command[2]: # Command has no argument, next completer is options # completer next_completer = command[0] state = "options" this_completer = command[0] # Non-exact match else: next_completer = command[0] this_completer = command[0] state = "options" # Appears to be a positional argument, grab next positional # completer and increment positional count else: if positional < len(command[1]): this_completer = command[1][positional] next_completer = command[0] state = "options" positional += 1 else: this_completer = command[0] next_completer = command[0] state = "options" else: # Completing an argument to a option/switch. We can't verify # it's legitimacy, so we assume it's right, and reset to a # default state. state = "options" this_completer = next_completer next_completer = command[0] if text.endswith(" "): yield from next_completer.get_completions(document, complete_event) else: yield from this_completer.get_completions(document, complete_event)
import pprint import random import sys from argparse import ArgumentParser from collections import defaultdict import requests from prompt_toolkit import HTML, PromptSession, print_formatted_text, prompt from prompt_toolkit.completion import WordCompleter VOTE_URL = '%s/vote/new' CHAIN_URL = '%s/chain' session = PromptSession() options = ['vote', 'add_node', 'chain', 'count', 'exit'] options_completer = WordCompleter(options) nodes = set() candidates = {1, 2, 3, 4, 5} def get_chain(): node = random.choice(list(nodes)) response = requests.get(CHAIN_URL % node) print() print_formatted_text(pprint.pformat(response.json())) def get_count(): node = random.choice(list(nodes)) response = requests.get(CHAIN_URL % node) chain = response.json()['chain']
parent: Posts {cats} --- """ import os from pathlib import Path p = Path(__file__) new_lr_file = p.parent / f"{iso_date}-{inflection.parameterize(title, separator='-')}.md" if os.path.exists(new_lr_file): raise Exception( f"Planned to create {new_lr_file} but a file already exists there!") with open(new_lr_file, "w") as f: f.write(frontmatter) print(f"""Wrote the below frontmatter to {new_lr_file} {frontmatter} You can now edit {new_lr_file} as required. """) start_vscode = yesno_to_bool( prompt(f"Run `code {new_lr_file}`? (yes/no) > ", validator=yesno_validator, completer=WordCompleter({'yes', 'no'})).lower()) if start_vscode: os.system(f"code {new_lr_file}")
def _config_completer(self): config_keys = self.hummingbot_application.config_able_keys() return WordCompleter(config_keys, ignore_case=True)
class HummingbotCompleter(Completer): def __init__(self, hummingbot_application): super(HummingbotCompleter, self).__init__() self.hummingbot_application = hummingbot_application # static completers self._path_completer = PathCompleter(get_paths=lambda: [f"./{CONF_FILE_PATH}"], file_filter=lambda fname: fname.endswith(".yml")) self._command_completer = WordCompleter(self.parser.commands, ignore_case=True) self._exchange_completer = WordCompleter(EXCHANGES, ignore_case=True) self._strategy_completer = WordCompleter(STRATEGIES, ignore_case=True) @property def prompt_text(self) -> str: return self.hummingbot_application.app.prompt_text @property def parser(self) -> ThrowingArgumentParser: return self.hummingbot_application.parser def get_subcommand_completer(self, first_word: str) -> Completer: subcommands: List[str] = self.parser.subcommands_from(first_word) return WordCompleter(subcommands, ignore_case=True) @property def _symbol_completer(self) -> Completer: symbol_fetcher = SymbolFetcher.get_instance() market = None for exchange in EXCHANGES: if exchange in self.prompt_text: market = exchange break symbols = symbol_fetcher.symbols.get(market, []) if symbol_fetcher.ready else [] return WordCompleter(symbols, ignore_case=True) @property def _wallet_address_completer(self): return WordCompleter(list_wallets(), ignore_case=True) @property def _option_completer(self): outer = re.compile("\((.+)\)") inner_str = outer.search(self.prompt_text).group(1) options = inner_str.split("/") if "/" in inner_str else [] return WordCompleter(options, ignore_case=True) @property def _config_completer(self): return WordCompleter(load_required_configs(), ignore_case=True) def _complete_strategies(self, document: Document) -> bool: return "strategy" in self.prompt_text def _complete_configs(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor return "config" in text_before_cursor def _complete_options(self, document: Document) -> bool: return "(" in self.prompt_text and ")" in self.prompt_text and "/" in self.prompt_text def _complete_exchanges(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor return "-e" in text_before_cursor or \ "--exchange" in text_before_cursor or \ "exchange" in self.prompt_text def _complete_symbols(self, document: Document) -> bool: return "symbol" in self.prompt_text def _complete_paths(self, document: Document) -> bool: return "path" in self.prompt_text and "file" in self.prompt_text def _complete_wallet_addresses(self, document: Document) -> bool: return "Which wallet" in self.prompt_text def _complete_command(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor return " " not in text_before_cursor and len(self.prompt_text.replace(">>> ", "")) == 0 def _complete_subcommand(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor index: int = text_before_cursor.index(' ') return text_before_cursor[0:index] in self.parser.commands def get_completions(self, document: Document, complete_event: CompleteEvent): """ Get completions for the current scope. This is the defining function for the completer :param document: :param complete_event: """ if self._complete_paths(document): for c in self._path_completer.get_completions(document, complete_event): yield c return if self._complete_strategies(document): for c in self._strategy_completer.get_completions(document, complete_event): yield c if self._complete_wallet_addresses(document): for c in self._wallet_address_completer.get_completions(document, complete_event): yield c elif self._complete_exchanges(document): for c in self._exchange_completer.get_completions(document, complete_event): yield c elif self._complete_symbols(document): for c in self._symbol_completer.get_completions(document, complete_event): yield c elif self._complete_command(document): for c in self._command_completer.get_completions(document, complete_event): yield c elif self._complete_configs(document): for c in self._config_completer.get_completions(document, complete_event): yield c elif self._complete_options(document): for c in self._option_completer.get_completions(document, complete_event): yield c else: text_before_cursor: str = document.text_before_cursor first_word: str = text_before_cursor[0:text_before_cursor.index(' ')] subcommand_completer: Completer = self.get_subcommand_completer(first_word) if complete_event.completion_requested or self._complete_subcommand(document): for c in subcommand_completer.get_completions(document, complete_event): yield c
echo(cli_table) def custom_print_green(value): return (echo(Fore.GREEN + value)) def custom_print_blue(value): return (echo(Fore.BLUE + value)) def custom_print_red(value): return (echo(Fore.RED + value)) command_completer = WordCompleter(sorted_commands, ignore_case=True) custom_print_blue(text2art('<< tasker >>')) custom_print_blue(''' tasker is a simple tool to track your daily/weekly tasks and export them as needed. You can add running tasks and start tracking the time right away or add paused tasks you can start later. Simply add a task and what project it belongs to. tasker will add it to your task list. Pause a task, or all tasks, and restar them later. tasker will aggregate total duration. End the task completely to let tasker know you are done with the task and it is ready to be exported. Press TAB to and scroll through to see the list of commands. ''') while 1: user_input = prompt(prompt_symbol,
def get_subcommand_completer(self, first_word: str) -> Completer: subcommands: List[str] = self.parser.subcommands_from(first_word) return WordCompleter(subcommands, ignore_case=True)
colorama.init() updateplug() except KeyboardInterrupt: pass for cmdex in pluginAPI.Plugins: for i in cmdex.retCmd(): cmds.append(i) for cmdex2 in root_pl.root_plugins: for i2 in cmdex2.retRootCmd(): cmds.append(i2) global completer completer = WordCompleter(cmds) global email_name email_name = 'zero' global direct global root global rootreg global forroot global reloading global email rootuse = False rootreg = bool(keyring.get_password('register', 'rootreg')) if rootreg == None: rootreg = False
def _option_completer(self): outer = re.compile("\((.+)\)") inner_str = outer.search(self.prompt_text).group(1) options = inner_str.split("/") if "/" in inner_str else [] return WordCompleter(options, ignore_case=True)
animal_completer = WordCompleter( [ "alligator", "ant", "ape", "bat", "bear", "beaver", "bee", "bison", "butterfly", "cat", "chicken", "crocodile", "dinosaur", "dog", "dolphin", "dove", "duck", "eagle", "elephant", "fish", "goat", "gorilla", "kangaroo", "leopard", "lion", "mouse", "rabbit", "rat", "snake", "spider", "turkey", "turtle", ], ignore_case=True, )
from prompt_toolkit import PromptSession from prompt_toolkit.completion import WordCompleter def show_help(): print("""Help -------- quit - quit this application exit - exit from this application eval - evaluate """) c = WordCompleter(["quit", "exit", "help", "eval"], ignore_case=True) s = PromptSession(completer=c) while True: cmd = s.prompt("Command: ") if cmd in {"quit", "Quit", "exit", "Exit"}: break elif cmd in {"help", "Help", "?"}: show_help() elif cmd == "eval": print("42")
'Proxy-Authorization', 'Range', 'Referer', 'TE', 'User-Agent', 'Upgrade', 'Via', 'Warning', ] header_values = [ 'application/json', 'text/html' ] headers_completer = WordCompleter(headers, ignore_case=True) header_values_completer = WordCompleter(header_values, ignore_case=True) class HeadersDialog: def __init__(self, event): def ok_handler(): result = add_headers_to_db(event, name) if result.get('success'): root_container.floats.pop() event.app.layout.focus(ButtonManager.prev_button) select_item(event)
import sqlite3 import pandas as pd from prompt_toolkit import PromptSession from prompt_toolkit.completion import WordCompleter from colorama import init from termcolor import colored from cmx import config as cfg init() my_completer = WordCompleter(['back', 'help', 'smb', 'list', 'creds', 'hosts', 'users', 'apps', 'az', 'exit'], ignore_case=True) genHelp = """Available Commands: help - Show Help Menu smb - Enter the SMB Database az - Enter the Azure Database exit - Exits CMXDB """ smbHelp = """Available Commands: back - Go back one level help - Show Help for this protocol help <command> - Show Help for command list - show available tables creds - List Credentials Stored in Database
def restconf(cfgp, curp, cnt, cfg, session): if cnt[curp]["type"] == "list" and cfgp.split("/")[-1] == curp.split( "/")[-1]: print "This operation is not supported at this level." else: completer = WordCompleter( ["GET", "POST", "PUT", "PATCH", "DELETE", "back"], ignore_case=True) text = session.prompt('select method> ', completer=completer, complete_while_typing=False) if text == "GET": print "\nExample request:\n" print "\tGET " + build_url(cfgp, curp, cnt, cfg) + " HTTP/1.1" print "\tHost: example.com" print "\tAccept: application/yang-data+json\n" elif text == "POST": auxurl = build_url(cfgp, curp, cnt, cfg) pprefix = cnt[curp]["orig"] url = '/'.join(auxurl.split("/")[:-1]) node = auxurl.split("/")[-1].split("=")[0] print "\nExample request:\n" print "\tPOST " + url + " HTTP/1.1" print "\tHost: example.com" print "\tAccept: application/yang-data+json\n" print( json.dumps( { pprefix + ":" + node: from_dict_to_rc(curp, cnt, find_json(cfgp, cfg), pprefix, True) }, indent=4, sort_keys=True) + "\n") #else: print(json.dumps({pprefix+":"+node:find_json(cfgp,cfg)}, indent=4, sort_keys=True)+"\n") elif text == "PUT": auxurl = build_url(cfgp, curp, cnt, cfg) pprefix = cnt[curp]["orig"] node = auxurl.split("/")[-1].split("=")[0] print "\nExample request:\n" print "\tPUT " + auxurl + " HTTP/1.1" print "\tHost: example.com" print "\tAccept: application/yang-data+json\n" print( json.dumps( { pprefix + ":" + node: from_dict_to_rc(curp, cnt, find_json(cfgp, cfg), pprefix, True) }, indent=4, sort_keys=True) + "\n") elif text == "PATCH": auxurl = build_url(cfgp, curp, cnt, cfg) pprefix = cnt[curp]["orig"] node = auxurl.split("/")[-1].split("=")[0] print "\nExample request:\n" print "\tPATCH " + auxurl + " HTTP/1.1" print "\tHost: example.com" print "\tAccept: application/yang-data+json\n" print( json.dumps( { pprefix + ":" + node: from_dict_to_rc(curp, cnt, find_json(cfgp, cfg), pprefix, True) }, indent=4, sort_keys=True) + "\n") elif text == "DELETE": print "\nExample request:\n" print "\tDELETE " + build_url(cfgp, curp, cnt, cfg) + " HTTP/1.1" print "\tHost: example.com" print "\tAccept: application/yang-data+json\n" else: print "Method not supported."
animal_completer = WordCompleter([ 'alligator', 'ant', 'ape', 'bat', 'bear', 'beaver', 'bee', 'bison', 'butterfly', 'cat', 'chicken', 'crocodile', 'dinosaur', 'dog', 'dolphin', 'dove', 'duck', 'eagle', 'elephant', 'fish', 'goat', 'gorilla', 'kangaroo', 'leopard', 'lion', 'mouse', 'rabbit', 'rat', 'snake', 'spider', 'turkey', 'turtle', ], ignore_case=True)
class HummingbotCompleter(Completer): def __init__(self, hummingbot_application): super(HummingbotCompleter, self).__init__() self.hummingbot_application = hummingbot_application self._path_completer = WordCompleter( file_name_list(CONF_FILE_PATH, "yml")) self._command_completer = WordCompleter(self.parser.commands, ignore_case=True) self._exchange_completer = WordCompleter(EXCHANGES, ignore_case=True) self._connect_exchange_completer = WordCompleter(CONNECT_EXCHANGES, ignore_case=True) self._export_completer = WordCompleter(["keys", "trades"], ignore_case=True) self._strategy_completer = WordCompleter(STRATEGIES, ignore_case=True) @property def prompt_text(self) -> str: return self.hummingbot_application.app.prompt_text @property def parser(self) -> ThrowingArgumentParser: return self.hummingbot_application.parser def get_subcommand_completer(self, first_word: str) -> Completer: subcommands: List[str] = self.parser.subcommands_from(first_word) return WordCompleter(subcommands, ignore_case=True) @property def _trading_pair_completer(self) -> Completer: trading_pair_fetcher = TradingPairFetcher.get_instance() market = None for exchange in EXCHANGES: if exchange in self.prompt_text: market = exchange break trading_pairs = trading_pair_fetcher.trading_pairs.get( market, []) if trading_pair_fetcher.ready else [] return WordCompleter(trading_pairs, ignore_case=True, sentence=True) @property def _wallet_address_completer(self): return WordCompleter(list_wallets(), ignore_case=True) @property def _option_completer(self): outer = re.compile(r"\((.+)\)") inner_str = outer.search(self.prompt_text).group(1) options = inner_str.split("/") if "/" in inner_str else [] return WordCompleter(options, ignore_case=True) @property def _config_completer(self): config_keys = self.hummingbot_application.config_able_keys() return WordCompleter(config_keys, ignore_case=True) def _complete_strategies(self, document: Document) -> bool: return "strategy" in self.prompt_text and "strategy file" not in self.prompt_text def _complete_configs(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor return "config" in text_before_cursor def _complete_options(self, document: Document) -> bool: return "(" in self.prompt_text and ")" in self.prompt_text and "/" in self.prompt_text def _complete_exchanges(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor return "-e" in text_before_cursor or \ "--exchange" in text_before_cursor or \ "connect" in text_before_cursor or \ any(x for x in ("exchange name", "name of exchange", "name of the exchange") if x in self.prompt_text.lower()) def _complete_connect_exchanges(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor return "connect" in text_before_cursor def _complete_export_options(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor return "export" in text_before_cursor def _complete_trading_pairs(self, document: Document) -> bool: return "trading pair" in self.prompt_text def _complete_paths(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor return (("path" in self.prompt_text and "file" in self.prompt_text) or "import" in text_before_cursor) def _complete_wallet_addresses(self, document: Document) -> bool: return "Which wallet" in self.prompt_text def _complete_command(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor return " " not in text_before_cursor and len( self.prompt_text.replace(">>> ", "")) == 0 def _complete_subcommand(self, document: Document) -> bool: text_before_cursor: str = document.text_before_cursor index: int = text_before_cursor.index(' ') return text_before_cursor[0:index] in self.parser.commands def get_completions(self, document: Document, complete_event: CompleteEvent): """ Get completions for the current scope. This is the defining function for the completer :param document: :param complete_event: """ if self._complete_paths(document): for c in self._path_completer.get_completions( document, complete_event): yield c elif self._complete_strategies(document): for c in self._strategy_completer.get_completions( document, complete_event): yield c elif self._complete_wallet_addresses(document): for c in self._wallet_address_completer.get_completions( document, complete_event): yield c elif self._complete_connect_exchanges(document): for c in self._connect_exchange_completer.get_completions( document, complete_event): yield c elif self._complete_export_options(document): for c in self._export_completer.get_completions( document, complete_event): yield c elif self._complete_exchanges(document): for c in self._exchange_completer.get_completions( document, complete_event): yield c elif self._complete_trading_pairs(document): for c in self._trading_pair_completer.get_completions( document, complete_event): yield c elif self._complete_command(document): for c in self._command_completer.get_completions( document, complete_event): yield c elif self._complete_configs(document): for c in self._config_completer.get_completions( document, complete_event): yield c elif self._complete_options(document): for c in self._option_completer.get_completions( document, complete_event): yield c else: text_before_cursor: str = document.text_before_cursor try: first_word: str = text_before_cursor[0:text_before_cursor. index(' ')] except ValueError: return subcommand_completer: Completer = self.get_subcommand_completer( first_word) if complete_event.completion_requested or self._complete_subcommand( document): for c in subcommand_completer.get_completions( document, complete_event): yield c
def _completer_for_command(self, command): if not hasattr(self, "_%s_completions" % command): return WordCompleter([]) return getattr(self, "_%s_completions" % command)()
def init(self, project_name='', template='base', quiet=False, debug=False): '''Generate new Foliant project.''' self.logger.setLevel(DEBUG if debug else WARNING) self.logger.info('Project creation started.') self.logger.debug(f'Template: {template}') template_path = Path(template) if not template_path.exists(): self.logger.debug( f'Template not found in {template_path}, looking in installed templates.' ) installed_templates_path = Path( Path(__file__).parent / 'templates') installed_templates = [ item.name for item in installed_templates_path.iterdir() if item.is_dir() ] self.logger.debug(f'Available templates: {installed_templates}') if template in installed_templates: self.logger.debug('Template found.') else: self.logger.debug('Template not found, asking for user input.') try: template = prompt( f'Please pick a template from {installed_templates}: ', completer=WordCompleter(installed_templates), validator=BuiltinTemplateValidator( installed_templates)) except KeyboardInterrupt: self.logger.warning('Project creation interrupted.') return template_path = installed_templates_path / template self.logger.debug(f'Template path: {template_path}') if not project_name: self.logger.debug( 'Project name not specified, asking for user input.') try: project_name = prompt('Enter the project name: ') except KeyboardInterrupt: self.logger.warning('Project creation interrupted.') return project_slug = slugify(project_name) project_path = Path(project_slug) properties = {'title': project_name, 'slug': project_slug} self.logger.debug(f'Project properties: {properties}') result = None with spinner('Generating project', self.logger, quiet, debug): copytree(template_path, project_path) text_types = '*.md', '*.yml', '*.txt', '*.py' text_file_paths = reduce(lambda acc, matches: acc + [*matches], (project_path.rglob(text_type) for text_type in text_types), []) for text_file_path in text_file_paths: self.logger.debug(f'Processing content of {text_file_path}') replace_placeholders(text_file_path, properties) for item in project_path.rglob('*'): self.logger.debug(f'Processing name of {item}') item.rename( Template(item.as_posix()).safe_substitute(properties)) result = project_path if result: self.logger.info(f'Result: {result}') if not quiet: print('─' * 20) print(f'Project "{project_name}" created in {result}') else: print(result) else: self.logger.critical('Project creation failed.') exit(1)
def main(device, interval, endpoint, script): global worker # Start send worker worker = threading.Thread(target=send_worker, args=(device, interval, endpoint), daemon=True) worker.start() cd = CommandDispatcher() # General commands cd.add_cmd('exit', parser=None, handler=do_exit) cd.add_cmd('quit', parser=None, handler=do_exit) cd.add_cmd('send', parser=None, handler=do_send) cd.add_cmd('delay = ', parser=IntParser(1, 86400), handler=do_delay) # Trigger commands cd.add_cmd('device_boot', parser=None, handler=trigger_device_boot) cd.add_cmd('manipulation', parser=None, handler=trigger_manipulation) cd.add_cmd('pir_motion', parser=None, handler=trigger_pir_motion) # Setter commands cd.add_cmd('batt_voltage = ', parser=FloatParser(0, 4.0), handler=set_batt_voltage) cd.add_cmd('humidity = ', parser=FloatParser(0, 100, 1), handler=set_humidity) cd.add_cmd('illuminance = ', parser=IntParser(0, 83000), handler=set_illuminance) cd.add_cmd('orientation = ', parser=IntParser(1, 6), handler=set_orientation) cd.add_cmd('reed_switch_1 = ', parser=IntParser(0, 1), handler=set_reed_switch_1) cd.add_cmd('reed_switch_2 = ', parser=IntParser(0, 1), handler=set_reed_switch_2) cd.add_cmd('temperature = ', parser=FloatParser(-40, 85, 2), handler=set_temperature) # Prioritize script execution over shell if script is not None: with open(script) as f: for line, cmd in enumerate(f): cmd = cmd.strip() if len(cmd) == 0: continue if not cd.dispatch(cmd): print( HTML( '<orangered>Invalid command (line {})</orangered>'. format(line + 1))) sys.exit(1) do_exit() # Pass list of all commands to completer completer = WordCompleter(cd.get_prefixes()) # Support prompt session with command history from file session = PromptSession(history=FileHistory('sticker_history')) # Process prompt commands in loop while True: cmd = session.prompt(HTML('<steelblue><b>sticker> </b></steelblue>'), completer=completer, complete_while_typing=True, auto_suggest=AutoSuggestFromHistory()) # Strip whitespace cmd = cmd.strip() # No processing for dummy commands if len(cmd) == 0: continue # Dispatch command if not cd.dispatch(cmd): print(HTML('<orangered>Invalid command</orangered>'))
def get_completer(): csv_files = [s for s in listdir() if s.endswith('.csv')] completions['load'] = WordCompleter(csv_files) completer = NestedCompleter.from_nested_dict(completions) return FuzzyCompleter(completer)
def __init__(self, shell): # type: (EqlShell) -> None """Completer for EQL shell.""" self.shell = shell self.command_completer = WordCompleter(lambda: shell.completenames(""), match_middle=True) self.path_completer = PathCompleter(expanduser=True)
def test_word_completer_match_middle(): completer = WordCompleter(["abc", "def", "abca"], match_middle=True) completions = completer.get_completions(Document("bc"), CompleteEvent()) assert [c.text for c in completions] == ["abc", "abca"]