コード例 #1
0
def generate_banner():
    talk_title = prompt("Enter the talk title: ")
    talk_speaker = prompt("Enter speaker's full name: ")
    months = [
        "January", "February", "March", "April", "May", "June", "July",
        "August", "September", "October", "November", "December"
    ]
    auto_complete_files = WordCompleter(months, ignore_case=True)
    talk_month = prompt("Which month the talk was recorded ?: ",
                        completer=auto_complete_files,
                        complete_while_typing=True)
    years = ["2017", "2018", "2019", "2020"]
    auto_complete_files = WordCompleter(years, ignore_case=True)
    talk_year = prompt("Which year the talk was presented ?: ",
                       completer=auto_complete_files,
                       complete_while_typing=True)

    command = ("""sed -e 's/%title%/{0}/g' -e 's/%speaker%/"""
               """{1}/g' -e 's/%month%/{2}/g' -e 's/%year%/"""
               """{3}/g' ./title-template.svg""").format(
                   talk_title, talk_speaker, talk_month, talk_year)
    args = shlex.split(command)
    with Halo(text="Generating banner...", spinner='dots'):
        with open("preface.svg", "w") as generated_content:
            subprocess.run(args, stdout=generated_content)
コード例 #2
0
    def get_completions(self, document, complete_event):

        text_before_cursor = document.text_before_cursor
        words_before_cursor = text_before_cursor.split(" ")

        if len(words_before_cursor) > 1:
            # Command is already complete
            command = words_before_cursor[0]

            if command in ["read"]:
                if len(words_before_cursor) == 2:
                    for completion in self.mbeans_with_attributes_completer.get_completions(document, complete_event):
                        yield completion
                elif len(words_before_cursor) == 3:
                    absolute_object_name = words_before_cursor[1]
                    if absolute_object_name in self.mbean_dict:
                        attributes = self.mbean_dict[absolute_object_name].attributes
                        attribute_completer = WordCompleter([attribute.attribute_name for attribute in attributes])
                        for completion in attribute_completer.get_completions(document, complete_event):
                            yield completion

        elif len(words_before_cursor) == 1:
            for possible_command in COMMANDS:
                if possible_command.startswith(words_before_cursor[0]):
                    yield Completion(possible_command, -len(possible_command))
コード例 #3
0
def create_completer(get_globals, get_locals, magics_manager, alias_manager):
    g = create_ipython_grammar()

    return GrammarCompleter(
        g, {
            'python':
            PythonCompleter(get_globals, get_locals),
            'magic':
            MagicsCompleter(magics_manager),
            'alias_name':
            AliasCompleter(alias_manager),
            'pdb_arg':
            WordCompleter(['on', 'off'], ignore_case=True),
            'autocall_arg':
            WordCompleter(['0', '1', '2'], ignore_case=True),
            'py_filename':
            PathCompleter(only_directories=False,
                          file_filter=lambda name: name.endswith('.py')),
            'filename':
            PathCompleter(only_directories=False),
            'directory':
            PathCompleter(only_directories=True),
            'system':
            SystemCompleter(),
        })
コード例 #4
0
def prompt_generator(form_title, fields):
    if os.name == 'nt':
        os.system('cls')
    else:
        os.system('clear')

    print(form_title)

    data = {}
    for field in fields:
        if field['type'] == 'TitleSelectOne':
            print('{} : '.format(field['name']))
            completer = WordCompleter(field['values'], ignore_case=True)
            for v in field['values']:
                print('- {}'.format(v))
            text = None

            while text not in field['values']:
                text = prompt('Enter your choice : ', completer=completer)

            data[field['key']] = text
        elif field['type'] == 'TitleSelect':
            print('{} : '.format(field['name']))
            completer = WordCompleter(field['values'], ignore_case=True)
            for v in field['values']:
                print('- {}'.format(v))
            data[field['key']] = prompt('Enter your choice or create new : ',
                                        completer=completer)
        elif field['type'] == 'TitlePassword':
            data[field['key']] = prompt('{} : '.format(field['name']),
                                        is_password=True)
        else:
            data[field['key']] = prompt('{} : '.format(field['name']))
        print('------------------------------')
    return data
コード例 #5
0
def select_service_and_operation():
    service_names = Session().get_available_services()
    service_completer = WordCompleter(service_names)
    service_name = prompt(u'Select service: ', completer=service_completer)
    if service_name not in service_names:
        click.secho(u'{} is not valid service'.format(service_name), fg='red')
        raise click.Abort()
    moto_client = get_moto_implementation(service_name)
    real_client = boto3.client(service_name, region_name='us-east-1')
    implemented = []
    not_implemented = []

    operation_names = [xform_name(op) for op in real_client.meta.service_model.operation_names]
    for op in operation_names:
        if moto_client and op in dir(moto_client):
            implemented.append(op)
        else:
            not_implemented.append(op)
    operation_completer = WordCompleter(operation_names)

    click.echo('==Current Implementation Status==')
    for operation_name in operation_names:
        check = 'X' if operation_name in implemented else ' '
        click.secho('[{}] {}'.format(check, operation_name))
    click.echo('=================================')
    operation_name = prompt(u'Select Operation: ', completer=operation_completer)

    if operation_name not in operation_names:
        click.secho('{} is not valid operation'.format(operation_name), fg='red')
        raise click.Abort()

    if operation_name in implemented:
        click.secho('{} is already implemented'.format(operation_name), fg='red')
        raise click.Abort()
    return service_name, operation_name
コード例 #6
0
def give():
    print("==============================")
    print("Choice customer from the list:")
    print("==============================")
    customers = {
        c[1].name: c[0]
        for c in enumerate(my_archive.get_items('customer'))
    }
    customers_completer = WordCompleter(customers.keys())

    for item in customers.keys():
        print("%s" % item)
    print()

    customer = prompt('customer ~> ', completer=customers_completer)
    customer_id = customers[customer]

    print("===========================")
    print("Choice which book you give:")
    print("===========================")
    books = {b.title: b for b in my_archive.get_items('book')}
    books_completer = WordCompleter(books.keys())

    for item in books.keys():
        print("%s" % item)
    print()

    book = prompt('book ~> ', completer=books_completer)

    try:
        my_archive.give_item(books[book], customer_id)
    except Exception as msg:
        print("====>> %s" % msg)
コード例 #7
0
ファイル: cmdbase.py プロジェクト: yishuihanhan/python-nubia
    def __init__(self, fn):
        self._built_in = False
        self._fn = fn

        if not callable(fn):
            raise ValueError("fn argument must be a callable")

        self._obj_metadata = inspect_object(fn)
        self._is_super_command = len(self.metadata.subcommands) > 0
        self._subcommand_names = []

        # We never expect a function to be passed here that has a self argument
        # In that case, we should get a bound method
        if "self" in self.metadata.arguments and not inspect.ismethod(
                self._fn):
            raise ValueError("Expecting either a function (eg. bar) or "
                             "a bound method (eg. Foo().bar). "
                             "You passed what appears to be an unbound method "
                             "(eg. Foo.bar) it has a 'self' argument: %s" %
                             function_to_str(fn))

        if not self.metadata.command:
            raise ValueError("function or class {} needs to be annotated with "
                             "@command".format(function_to_str(fn)))
        # If this is a super command, we need a completer for sub-commands
        if self.super_command:
            self._commands_completer = WordCompleter([],
                                                     ignore_case=True,
                                                     sentence=True)
            for _, inspection in self.metadata.subcommands:
                _sub_name = inspection.command.name
                self._commands_completer.words.append(_sub_name)
                self._commands_completer.meta_dict[_sub_name] = dedent(
                    inspection.command.help).strip()
                self._subcommand_names.append(_sub_name)
コード例 #8
0
ファイル: utils.py プロジェクト: element568/neo-cli
def prompt_generator(form_title, fields):
    if os.name == "nt":
        os.system("cls")
    else:
        os.system("clear")

    print(form_title)

    data = {}
    for field in fields:
        if field["type"] == "TitleSelectOne":
            print("{} : ".format(field["name"]))
            completer = WordCompleter(field["values"], ignore_case=True)
            for v in field["values"]:
                print("- {}".format(v))
            text = None

            while text not in field["values"]:
                text = prompt("Enter your choice : ", completer=completer)

            data[field["key"]] = text
        elif field["type"] == "TitleSelect":
            print("{} : ".format(field["name"]))
            completer = WordCompleter(field["values"], ignore_case=True)
            for v in field["values"]:
                print("- {}".format(v))
            data[field["key"]] = prompt("Enter your choice or create new : ",
                                        completer=completer)
        elif field["type"] == "TitlePassword":
            data[field["key"]] = prompt("{} : ".format(field["name"]),
                                        is_password=True)
        else:
            data[field["key"]] = prompt("{} : ".format(field["name"]))
        print("------------------------------")
    return data
コード例 #9
0
def checkUpload():
    from menu import clientMenuOptions
    use_client_upload = prompt_toolkit.prompt(
        '\n[?] Upload Using Client Connection? [y]/n: ',
        patch_stdout=True,
        completer=WordCompleter(['y', 'n']))
    print
    if use_client_upload.lower() == 'y' or use_client_upload == '':
        clientList = []
        for i in clientMenuOptions.keys():
            if i == 'back' or i == 'r':
                pass
            else:
                clientList.append(i)
                print t.bold_yellow + i + t.normal + ': ' + t.bold_green + clientMenuOptions[
                    i]['payload'] + t.bold_yellow + ' | ' + t.bold_green + clientMenuOptions[
                        i]['availablemodules'].keys(
                        )[0] + t.bold_yellow + ' | ' + t.bold_green + clientMenuOptions[
                            i]['availablemodules'].keys()[1] + t.normal
        print
        while True:
            clientchoice = prompt_toolkit.prompt(
                'Client > ',
                patch_stdout=True,
                style=prompt_toolkit.styles.style_from_dict(
                    {prompt_toolkit.token.Token: '#FFCC66'}),
                completer=WordCompleter(clientList))
            try:
                return int(clientMenuOptions[clientchoice]['params'])
            except:
                continue
    return False
コード例 #10
0
ファイル: interface.py プロジェクト: glennq/bgmcli
def run():
    """The function that runs the CLI"""
    backend = CLIBackend(*read_config())
    history = InMemoryHistory()
    completer = WordCompleter(backend.get_completion_list())
    user_id = backend.get_user_id()

    while True:
        try:
            text = get_input(
                user_id + '> ',
                completer=completer,
                history=history,
                on_abort=AbortAction.RETRY,
                key_bindings_registry=key_bindings_manager.registry)
        except EOFError:
            # Control-D pressed.
            break
        else:
            if text.strip() == 'exit':
                break
            try:
                backend.execute_command(text)
            except CommandError as e:
                print e.message
            except Exception:
                backend.close()
                raise
            else:
                # update word completer
                completer = WordCompleter(backend.get_completion_list())

    backend.close()
コード例 #11
0
ファイル: desc-lambdas.py プロジェクト: d66pak/mybin
def main():
	# Get the AWS profile from user
	profileCompleter = WordCompleter(['default', 'tkt_prod_ro'], ignore_case=True)
	profile = prompt('AWS profile: ',
		history=FileHistory('profile-history.txt'),
		auto_suggest=AutoSuggestFromHistory(),
		completer=profileCompleter
		)

	# Create session and client
	session = boto3.session.Session(profile_name=profile)
	client = session.client('lambda')

	# Get the list of lambdas
	l_lambdas = llambdas.llambdas(client)
	l_lambdaName = [d_function['FunctionName'] for d_function in l_lambdas]

	lambdaCompleter = WordCompleter(l_lambdaName, ignore_case=True)
	lambdaName = prompt('Lambda name: ',
		history=FileHistory('lambda-history.txt'),
		auto_suggest=AutoSuggestFromHistory(),
		completer=lambdaCompleter
		)

	prettyPrintJson(filter(lambda d_function: d_function['FunctionName'] == lambdaName, l_lambdas))

	print ''
	print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
	print ''
	# Event source mapping
	d_resp = client.list_event_source_mappings(FunctionName=lambdaName)
	prettyPrintJson(d_resp['EventSourceMappings'])
コード例 #12
0
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))
コード例 #13
0
ファイル: completer.py プロジェクト: tony/pymux
    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)
コード例 #14
0
ファイル: cli.py プロジェクト: nuaays/argo
 def node_completions(node):
     vals = getattr(node, "values", None)
     if callable(vals):
         arr_vals = vals(node)
         setattr(node, "values", arr_vals)
         return WordCompleter(arr_vals)
     elif isinstance(vals, list):
         return WordCompleter(vals)
     else:
         return None
コード例 #15
0
    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)
コード例 #16
0
    def __init__(self, parser, listeners):
        self._completer = WordCompleter([], ignore_case=True, sentence=True)
        # maps a command to Command Instance
        self._cmd_instance_map = {}
        # objects interested in receiving messages
        self._listeners = []
        # argparser so each command can add its options
        self._parser = parser

        for lst in listeners:
            self.register_listener(lst(self))
コード例 #17
0
ファイル: cmdex.py プロジェクト: huleiak47/python-hlutils
    def __init__(self):
        GIT_CMDS = [
            "add", "gc", "receive-pack", "add--interactive", "get-tar-commit-id",
            "reflog", "am", "grep", "relink", "annotate", "gui", "remote", "apply",
            "gui--askpass", "remote-ext", "archimport", "gui--askyesno",
            "remote-fd", "archive", "gui.tcl", "remote-ftp", "bisect",
            "hash-object", "remote-ftps", "bisect--helper", "help", "remote-http",
            "blame", "http-backend", "remote-https", "branch", "http-fetch",
            "repack", "bundle", "http-push", "replace", "cat-file", "imap-send",
            "request-pull", "check-attr", "index-pack", "rerere", "check-ignore",
            "init", "reset", "check-mailmap", "init-db", "rev-list", "check-ref-format",
            "instaweb", "rev-parse", "checkout", "interpret-trailers", "revert",
            "checkout-index", "log", "rm", "cherry", "ls-files", "send-email",
            "cherry-pick", "ls-remote", "send-pack", "citool", "ls-tree",
            "sh-i18n--envsubst", "clean", "mailinfo", "shortlog", "clone",
            "mailsplit", "show", "column", "merge", "show-branch", "commit",
            "merge-base", "show-index", "commit-tree", "merge-file", "show-ref",
            "config", "merge-index", "stage", "count-objects", "merge-octopus",
            "stash", "credential", "merge-one-file", "status", "credential-store",
            "merge-ours", "stripspace", "credential-wincred", "merge-recursive",
            "submodule", "cvsexportcommit", "merge-resolve", "submodule--helper",
            "cvsimport", "merge-subtree", "subtree", "cvsserver", "merge-tree",
            "svn", "daemon", "mergetool", "symbolic-ref", "describe",
            "mktag", "tag", "diff", "mktree", "unpack-file", "diff-files",
            "mv", "unpack-objects", "diff-index", "name-rev", "update-index",
            "diff-tree", "notes", "update-ref", "difftool", "p4", "update-server-info",
            "difftool--helper", "pack-objects", "upload-archive", "fast-export",
            "pack-redundant", "upload-pack", "fast-import", "pack-refs", "var",
            "fetch", "patch-id", "verify-commit", "fetch-pack", "prune",
            "verify-pack", "filter-branch", "prune-packed", "verify-tag",
            "fmt-merge-msg", "pull", "web--browse", "for-each-ref", "push",
            "whatchanged", "format-patch", "quiltimport", "worktree",
            "fsck", "read-tree", "write-tree", "fsck-objects", "rebase",
        ]
        # get alias
        try:
            config = os.path.expanduser("~/.gitconfig")
            if os.path.exists(config):
                start = False
                for line in open(config):
                    if line.strip() == "[alias]":
                        start = True
                    elif line.startswith("["):
                        start = False
                    elif line.strip().startswith("#"):
                        pass
                    else:
                        if "=" in line:
                            GIT_CMDS.append(line.split("=")[0].strip())
        except OSError:
            pass

        GIT_CMDS.sort(cmp=lambda x, y: len(x) - len(y))
        WordCompleter.__init__(self, GIT_CMDS)
コード例 #18
0
ファイル: cmdex.py プロジェクト: huleiak47/python-hlutils
 def __init__(self):
     SVN_CMDS = [
         "add", "auth", "blame", "praise", "annotate", "ann", "cat", "changelist",
         "cl", "checkout", "co", "cleanup", "commit", "ci", "copy", "cp",
         "delete", "del", "remove", "rm", "diff", "di", "export", "help",
         "?", "h", "import", "info", "list", "ls", "lock", "log", "merge",
         "mergeinfo", "mkdir", "move", "mv", "rename", "ren", "patch", "propdel",
         "pdel", "pd", "propedit", "pedit", "pe", "propget", "pget", "pg",
         "proplist", "plist", "pl", "propset", "pset", "ps", "relocate",
         "resolve", "resolved", "revert", "status", "stat", "st", "switch",
         "sw", "unlock", "update", "up", "upgrade",
     ]
     SVN_CMDS.sort(cmp=lambda x, y: len(x) - len(y))
     WordCompleter.__init__(self, SVN_CMDS)
コード例 #19
0
def start():

    g = create_grammar()

    lexer = GrammarLexer(g, lexers={
        'op_mac': SimpleLexer(Token.Operator),
        'op_main': SimpleLexer(Token.Operator),
        'op_instance': SimpleLexer(Token.Operator),
        'op_configuration': SimpleLexer(Token.Operator),
        'op_infrastructure': SimpleLexer(Token.Operator),
        'op_parameter': SimpleLexer(Token.Text),
        })

    completer = GrammarCompleter(g, {
        'op_main': WordCompleter(op_main),
        'op_instance': WordCompleter(op_instance),
        'op_configuration': WordCompleter(op_configuration),
        'op_infrastructure': WordCompleter(op_infrastructure),
        })

    history = InMemoryHistory()

    parser = maccli.mac_cli.initialize_parser()

    show("Start typing 'mac', CTRL+C to exit")
    user_aborted = False
    program_running = True
    while program_running:
        try:
            text = prompt('> ', lexer=lexer, completer=completer, style=MacStyle, history=history, auto_suggest=AutoSuggestFromHistory())
            argv_raw = shlex.split(text)
            argv = maccli.mac_cli.patch_help_option(argv_raw)
            args = parser.parse_args(argv)
            maccli.mac_cli.dispatch_cmds(args)
            user_aborted = False
        except InternalError as e:
            maccli.logger.debug("Code raised Internal Error", e)
            pass
        except EOFError as e:
            maccli.logger.debug("Code raised EOFError", e)
            pass
        except KeyboardInterrupt as e:
            maccli.logger.debug("Code raised KeyboardInterrupt", e)
            if user_aborted:
                program_running = False
            else:
                user_aborted = True
                show("Press CTRL+C again to exit")
            pass
コード例 #20
0
ファイル: completer.py プロジェクト: PabloSajnovsky/pymux
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
コード例 #21
0
 def run(self):
     """Runs the interface and waits for user input commands."""
     completer = WordCompleter([
         'show', 'name', 'layer', 'dump', 'layers', 'preconditions',
         'postconditions', 'executions', 'intercept', 'timestamp',
         'version', 'save', 'description', 'spoof', 'clear', 'back'
     ])
     # Initialization of the command history
     history = FileHistory(join(self._polym_path, '.tinterface_history'))
     while True:
         try:
             command = prompt(HTML("<bold>PH:cap/<red>t%d</red> > </bold>" %
                                   self._index),
                              history=history,
                              completer=completer,
                              complete_style=CompleteStyle.READLINE_LIKE,
                              auto_suggest=AutoSuggestFromHistory(),
                              enable_history_search=True)
         except KeyboardInterrupt:
             self.exit_program()
             continue
         command = command.split(" ")
         if command[0] in self.EXIT:
             self.exit_program()
         elif command[0] in self.RET:
             break
         elif command[0] == "name":
             self._name(command)
         elif command[0] in ["dump", "d"]:
             self._dump(command)
         elif command[0] in ["layer", "l"]:
             self._layer(command)
         elif command[0] in ['precs', 'preconditions']:
             self._conditions(command, 'preconditions')
         elif command[0] in ['posts', 'postconditions']:
             self._conditions(command, 'postconditions')
         elif command[0] in ['execs', 'executions']:
             self._conditions(command, 'executions')
         elif command[0] in ["show", "s"]:
             self._show(command)
         elif command[0] in ["intercept", "i"]:
             self._intercept(command)
         elif command[0] in ["layers", "ls"]:
             self._layers(command)
         elif command[0] == "timestamp":
             print(self._t.timestamp, '\n')
         elif command[0] == "version":
             self._version(command)
         elif command[0] in ['desc', 'description']:
             self._description(command)
         elif command[0] == "save":
             self._save(command)
         elif command[0] in ["spoof"]:
             self._spoof(command)
         elif command[0] == "clear":
             Interface._clear()
         elif command[0] == "":
             continue
         else:
             Interface._wrong_command()
コード例 #22
0
ファイル: input.py プロジェクト: whitef0x0/gtd.py
 def manipulate_attachments(card):
     '''Give the user a CRUD interface for attachments on this card'''
     print('Enter a URL, "delete", "open", "print", or Enter to exit')
     user_input = 'Nothing really'
     attachment_completer = WordCompleter(
         ['delete', 'print', 'open', 'http://', 'https://'],
         ignore_case=True)
     while user_input != '':
         user_input = prompt('attach > ',
                             completer=attachment_completer).strip()
         if re.search(VALID_URL_REGEX, user_input):
             # attach this link
             card.attach(url=user_input)
             print('Attached {0}'.format(user_input))
         elif user_input in ['delete', 'open']:
             attachment_opts = {a.name: a for a in card.get_attachments()}
             if not attachment_opts:
                 print('No attachments')
                 continue
             dest = single_select(attachment_opts.keys())
             if dest is not None:
                 target = attachment_opts[dest]
                 if user_input == 'delete':
                     card.remove_attachment(target.id)
                 elif user_input == 'open':
                     with DevNullRedirect():
                         webbrowser.open(target.url)
         elif user_input == 'print':
             existing_attachments = card.get_attachments()
             if existing_attachments:
                 print('Attachments:')
                 for a in existing_attachments:
                     print('  ' + a.name)
コード例 #23
0
    def get_completer(self):

        standard_completions = ['block', 'tx', 'header', 'mem', 'neo', 'gas',
                                'help', 'state', 'nodes', 'exit', 'quit',
                                'config', 'import', 'export', 'open',
                                'wallet', 'contract', 'asset', 'wif',
                                'watch_addr', 'contract_addr', 'testinvoke', 'tkn_send',
                                'tkn_mint', 'tkn_send_from', 'tkn_approve', 'tkn_allowance',
                                'build', ]

        if self.Wallet:
            for addr in self.Wallet.Addresses:
                if addr not in self._known_things:
                    self._known_things.append(addr)
            for alias in self.Wallet.NamedAddr:
                if alias.Title not in self._known_things:
                    self._known_things.append(alias.Title)
            for tkn in self.Wallet.GetTokens().values():
                if tkn.symbol not in self._known_things:
                    self._known_things.append(tkn.symbol)

        all_completions = standard_completions + self._known_things

        completer = WordCompleter(all_completions)

        return completer
コード例 #24
0
ファイル: stager.py プロジェクト: mmg1/Winpayloads
def interactShell(clientnumber):
    clientnumber = int(clientnumber)
    from menu import clientMenuOptions
    for server in serverlist:
        if clientnumber in server.handlers.keys():
            print "Commands\n" + "-" * 50 + "\nback - Background Shell\nexit - Close Connection\n" + "-" * 50
            while True:
                if server.handlers[clientnumber].in_buffer:
                    print server.handlers[clientnumber].in_buffer.pop()
                command = prompt_toolkit.prompt("PS >",
                                                completer=WordCompleter(
                                                    ['back', 'exit']),
                                                history=history)
                if command.lower() == "back":
                    break
                if command.lower() == "exit":
                    server.handlers[clientnumber].handle_close()
                    del clientMenuOptions[str(clientnumber)]
                    time.sleep(2)
                    break
                if command == "":
                    server.handlers[clientnumber].out_buffer.append(
                        '{"type":"", "data":"", "sendoutput":""}')
                else:
                    json = '{"type":"exec", "data":"%s", "sendoutput":"true"}' % (
                        (base64.b64encode(command.encode('utf_16_le'))))
                    server.handlers[clientnumber].out_buffer.append(json)
                    while not server.handlers[clientnumber].in_buffer:
                        time.sleep(0.01)
                    print server.handlers[clientnumber].in_buffer.pop()

    return "clear"
コード例 #25
0
ファイル: prompt.py プロジェクト: zippyy/Pytify
def completer():
    list = []

    for name in history():
        list.append(name)

    return WordCompleter(set(list), ignore_case=True)
コード例 #26
0
ファイル: cli.py プロジェクト: singajeet/ide
 def __test_register_commands(self):
     """docstring for register_commands"""
     #-------------------- COMMAND => [NEW] SUB-COMMAND => [CATEGORY] --------------------
     cmd = 'NEW'
     cmd_description = 'Help in creating new object passed as sub-command'
     sub_cmd = 'CATEGORY'
     sub_cmd_description = 'The Category object available in AIML namespace'
     sub_cmd_kw_opts = {'PATTERN':'', 'TEMPLATE':'', 'SYSTEM':'',\
             'REF_THAT':'', 'REF_TOPIC':'', 'FORWARD_TO':''}
     sub_cmd_opts = {'--USE_DEFAULTS': False}
     sub_cmd_required = ['PATTERN', 'TEMPLATE']
     #-------------------- Register Commands --------------------
     self._parser.register_command(cmd, description\
             =cmd_description, prompt_tokens_callback\
             =self.get_cmd_prompt_tokens, \
             cmd_processor_callback\
             =self.__test_new_cmd_callback)
     self._parser.register_sub_command(cmd, sub_cmd,\
             description=sub_cmd_description,\
             prompt_tokens_callback\
             =self.get_sub_cmd_prompt_tokens,
             cmd_processor_callback=\
                     self.__test_new_category_sub_cmd_callback,
             options=sub_cmd_opts,\
             kw_options=sub_cmd_kw_opts,\
             required_fields=sub_cmd_required)
     #-------------------- End Register Commands --------------------
     #-------------------- Populate command completer dicts --------------------
     cmd_completer = self._parser.get_cmd_completer()
     self._cmd_completer = WordCompleter(cmd_completer[0], meta_dict=cmd_completer[1], ignore_case=True)
コード例 #27
0
 def singleplayer_mainloop(self,
                           player_connection: PlayerConnection) -> None:
     """Main event loop for the console I/O adapter for single player mode"""
     while not self.stop_main_loop:
         # Input a single line of text by the player. It is stored in the internal
         # command buffer of the player. The driver's main loop can look into that
         # to see if any input should be processed.
         self.input_not_paused.wait()
         try:
             # note that we don't print any prompt ">>", that needs to be done
             # by the main thread that handles screen *output*
             # (otherwise the prompt will often appear before any regular screen output)
             old_player = player_connection.player
             # do blocking console input call
             if prompt_toolkit and self.do_prompt_toolkit:
                 # word completion for the names of things and people
                 all_candidates = self.tab_complete_get_all_candidates(
                     mud_context.driver)
                 completer = WordCompleter(all_candidates)
                 # unfortunately prompt_toolkit doesn't allow ansi style codes in the prompt so we use a plain one.
                 cmd = prompt_toolkit.prompt("\n>> ",
                                             patch_stdout=True,
                                             completer=completer,
                                             complete_while_typing=False)
             else:
                 cmd = input()
             player_connection.player.store_input_line(cmd)
             if old_player is not player_connection.player:
                 # this situation occurs when a save game has been restored,
                 # we also have to unblock the old_player
                 old_player.store_input_line(cmd)
         except KeyboardInterrupt:
             self.break_pressed()
         except EOFError:
             pass
コード例 #28
0
    def onArrowKeyUP(self, event):
        self.animal_completer = WordCompleter([
            'alligator',
            'ant',
            'ape',
            'bat',
            'bear',
            'beaver',
            'bee',
            'bison',
            'butterfly',
            'cat',
        ],
                                              ignore_case=True)
        self.completer = self.animal_completer
        self.complete_while_typing = False
        self.note.text.insert("end", self.completer.words)

        self.note.text.insert("end", "\n")
        self.note.text.insert("end", "\n")
        self.note.text.insert("end", "get_completions\n")
        self.note.text.insert("end", self.completer.get_completions)
        self.note.text.insert("end", "\n")

        self.note.text.insert("end", "\n")
        self.note.text.insert("end", "completer.words\n")
        for word in self.completer.words:
            self.note.text.insert("end", word + "\n")
        print(str(dir(self.completer)))

        #################################################################
        #                     AUTO-SUGGESTION                           #
        #################################################################
        '''our_history = FileHistory('.example-history-file')
コード例 #29
0
ファイル: musixli.py プロジェクト: yathartha1/MusixLI
class musixli:
    musix_completer = WordCompleter([
        'artists', 'songs', 'search', 'albums', 'related_artists', 'lyrics',
        'clear', '--country', '--song', '--artist-name', '--number',
        '--browser'
    ],
                                    ignore_case=True)

    def __init__(self):
        def get_toolbar(self):
            return [(Token.Toolbar.Status.Key, '[msx] Help      [ctrl+q] Exit')
                    ]

        updated_style = style_from_pygments(
            TangoStyle, {
                Token.Menu.Completions.Completion.Current:
                'bg:#acba36 #000000',
                Token.Menu.Completions.Completion: 'bg:#008888 #ffffff',
                Token.Menu.Completions.ProgressBar: 'bg:#acba36',
                Token.Scrollbar: 'bg:#acba36',
                Token.Scrollbar.Button: 'bg:#003333',
                Token.Toolbar: '#ffffff bg:#333333',
                Token: '#00ffff bold',
                Token.Toolbar.Status.Key: '#ff0000'
            })
        history = InMemoryHistory()
        layout = create_default_layout(message=u'musixli:$>> ',
                                       get_bottom_toolbar_tokens=get_toolbar)
        cli_buffer = Buffer(history=history,
                            auto_suggest=AutoSuggestFromHistory(),
                            enable_history_search=True,
                            completer=self.musix_completer,
                            complete_while_typing=Always(),
                            accept_action=AcceptAction.RETURN_DOCUMENT)
        loop = create_eventloop()
        self.manager = KeyBindingManager()

        @self.manager.registry.add_binding(Keys.ControlQ, eager=True)
        def exit_(event):
            sys.exit()

        application = Application(
            key_bindings_registry=self.manager.registry,
            layout=layout,
            mouse_support=False,
            buffer=cli_buffer,
            style=updated_style,
            ignore_case=True,
        )
        self.cli = CommandLineInterface(application=application,
                                        eventloop=loop)

    def commands(self, document):
        command = document.text
        subprocess.call(command, shell=True)

    def start(self):
        while True:
            document = self.cli.run(reset_current_buffer=True)
            self.commands(document)
コード例 #30
0
    def act(self, game_state, reward, done):
        if (self.walkthrough and game_state._compute_intermediate_reward
                and len(game_state.policy_commands) > 0
                and not game_state.game_ended):
            text = '[{:02.1%}|({}): {}]\n'.format(
                game_state.score, game_state.intermediate_reward,
                " > ".join(game_state.policy_commands))
            print("Walkthrough: {}\n".format(text))

        if prompt_toolkit_available:
            actions_completer = None
            if self.autocompletion and hasattr(game_state,
                                               "admissible_commands"):
                actions_completer = WordCompleter(
                    game_state.admissible_commands,
                    ignore_case=True,
                    sentence=True)
            action = prompt('> ',
                            completer=actions_completer,
                            history=self._history,
                            enable_history_search=True)
        else:
            if self.autocompletion and hasattr(game_state,
                                               "admissible_commands"):
                print("Available actions: {}\n".format(
                    game_state.admissible_commands))

            action = input('> ')

        return action
コード例 #31
0
    def input_non_project_object(self, area):
        use_last_objects = self.config.get_area(area).get(
            "use_last_objects", False)
        last_objects = []
        if use_last_objects:
            last_objects = self.db.get_last_objects(
                area, self.config.get_num_last_objects())
            last_objects_dict = {
                "[{0}]".format(x): k[0]
                for x, k in enumerate(last_objects)
            }
            # Transform last objects into [x]: object tags
            if len(last_objects) > 0:
                p = Printer()
                last_objects_dict = {
                    "[{0}]".format(x): k
                    for x, k in enumerate(last_objects)
                }
                p.add("Last {0} {1} Objects :: ".format(
                    len(last_objects), area))
                p.newline()
                for k, v in sorted(last_objects_dict.items()):
                    p.add("{0} {1}".format(k, v))
                p.newline()
                p.print()
        object = prompt("Object :: ",
                        completer=WordCompleter(last_objects),
                        vi_mode=True)
        if use_last_objects:
            if object in last_objects_dict:
                return last_objects_dict[object]

        return object
コード例 #32
0
def generate_ability_scores(ability_generator_method):
    print('Generating ability scores using the {} method'.format(
        ability_generator_method))
    if ability_generator_method == 'Standard':
        print('\nGenerating 6 numbers for your abilities...')
        ability_rolls = 6
        ability_results = []
        while ability_rolls > 0:
            ability_results.append(make_ability_roll())
            ability_rolls -= 1

        print('Your roll totals were', ability_results)
        ability_option_completer = WordCompleter(ABILITIES)
        ability_options = ABILITIES.copy()
        ability_selection = {}
        for result in ability_results:
            ability = prompt(
                '\nWhich ability would you like to apply roll {} to?'
                '\n\nAbilities are: {}\n\n>>> '.format(
                    result, ', '.join(ability_options)),
                completer=ability_option_completer,
                validator=AbilityValidator())
            ability_selection[ability] = result
            ability_options.remove(ability)

        print(ability_selection)
コード例 #33
0
ファイル: cmdex.py プロジェクト: huleiak47/python-hlutils
class ExecutableCompleter(Completer):
    """
    Complete only excutable files in the current path.
    """

    def __init__(self):
        self.pathcompleter = PathCompleter(
            only_directories=False,
            expanduser=True)
        self.wordcompleter = WordCompleter(CMDEXE_INT_CMDS + _InternalCmds.keys(), ignore_case=True)

    def get_completions(self, document, complete_event):
        text_prefix = document.text_before_cursor

        # windows cmd.exe command
        for completion in self.wordcompleter.get_completions(
                document, complete_event):
            yield completion

        # executeable in PATH
        for _dir in os.environ["PATH"].split(os.pathsep):
            if not os.path.exists(_dir):
                continue
            for f in os.listdir(_dir):
                if f.lower().startswith(text_prefix.lower()) \
                        and os.path.isfile(os.path.join(_dir, f)) \
                        and os.path.splitext(f)[1].lower() in EXE_EXTS:
                    yield Completion(f, -len(text_prefix), display=f)

        # current dir files
        for completion in self.pathcompleter.get_completions(
                document, complete_event):
            yield completion
コード例 #34
0
ファイル: prompt.py プロジェクト: neilkakkar/prisma-core
 def __init__(self):
     # prepare websocket client
     self.info_peer_count = 0
     self.info_last_event_time = False
     self.info_my_balance = False
     self.info_my_address = False
     self.block = False
     self.client_factory = ClientFactory(url='ws://127.0.0.1:{}'.format(Prisma().api.port))
     self.client_factory.prompt = self
     self.client_connection = connectWS(self.client_factory)
     # prompt style
     self.print_style_green = style_from_dict({
         Token.Text: '#00cc00',
     })
     self.print_style_red = style_from_dict({
         Token.Text: '#cc0000',
     })
     self.prompt_style = style_from_dict({
         Token.Pound:    '#ffff00',
         Token.Toolbar:  '#00ee00 bg:#333333',
     })
     # prompt autocompletion
     words = []
     for command in self.command_list:
         words.append(command['command'])
     self.completer = WordCompleter(words, ignore_case=True, sentence=True)
     # prompt memory
     self.history = FileHistory(expanduser('~/.prisma/history.txt'))
コード例 #35
0
def interactShell(clientnumber):
    clientnumber = int(clientnumber)
    from menu import clientMenuOptions
    for server in serverlist:
        if clientnumber in server.handlers.keys():
            print "Commands\n" + "-" * 50 + "\nback - Background Shell\nexit - Close Connection\n" + "-" * 50
            while True:
                if server.handlers[clientnumber].in_buffer:
                    print server.handlers[clientnumber].in_buffer.pop()
                command = prompt_toolkit.prompt("PS >",
                                                completer=WordCompleter(
                                                    ['back', 'exit']),
                                                history=history)
                if command.lower() == "back":
                    break
                elif command.lower() == "exit":
                    server.handlers[clientnumber].handle_close()
                    del clientMenuOptions[str(clientnumber)]
                    time.sleep(2)
                    break
                elif command == "":
                    pass
                else:
                    server.handlers[clientnumber].out_buffer.append(command)
                    while not server.handlers[clientnumber].in_buffer:
                        time.sleep(0.01)
                    print server.handlers[clientnumber].in_buffer.pop()

    return "clear"
コード例 #36
0
ファイル: maininterface.py プロジェクト: sUbc0ol/polymorph
 def run(self):
     """Runs the interface and waits for user input commands."""
     completer = WordCompleter(['capture', 'spoof', 'clear'])
     history = FileHistory(self._polym_path + '/.minterface_history')
     while True:
         try:
             command = prompt(HTML("<bold><red>PH</red> > </bold>"),
                              history=history,
                              completer=completer,
                              complete_style=CompleteStyle.READLINE_LIKE,
                              auto_suggest=AutoSuggestFromHistory(),
                              enable_history_search=True)
         except KeyboardInterrupt:
             self.exit_program()
             continue
         command = command.split(" ")
         if command[0] in self.EXIT:
             self.exit_program()
         elif command[0] in ["capture", "c"]:
             self._capture(command)
         elif command[0] in ["spoof", "s"]:
             self._spoof(command)
         elif command[0] == "clear":
             Interface._clear()
         elif command[0] == "":
             continue
         else:
             Interface._wrong_command()
コード例 #37
0
    def __init__(self, mbeans):
        self.mbean_dict = {mbean.absolute_object_name: mbean for mbean in mbeans}

        self.mbeans_with_attributes_completer = WordCompleter(
            [mbean.absolute_object_name for mbean in mbeans if len(mbean.attributes) > 0])
コード例 #38
0
ファイル: cmdex.py プロジェクト: huleiak47/python-hlutils
 def __init__(self):
     self.pathcompleter = PathCompleter(
         only_directories=False,
         expanduser=True)
     self.wordcompleter = WordCompleter(CMDEXE_INT_CMDS + _InternalCmds.keys(), ignore_case=True)