Пример #1
0
def getinput(question,
             default="",
             reader=raw_input,
             completer=None,
             width=_defaultwidth):  # pragma: no cover
    """
    http://stackoverflow.com/questions/2617057/\
            supply-inputs-to-python-unittests
    """
    if reader == raw_input:
        if not _readline_available:
            val = raw_input(question.ljust(width))
            if val:
                return val
            else:
                return default
        else:

            def defaulter():
                """define default behavior startup"""
                readline.insert_text(default)

            if _readline_available:
                readline.set_startup_hook(defaulter)
                readline.get_completer()
                readline.set_completer(completer)

            x = raw_input(question.ljust(width))

            if _readline_available:
                readline.set_startup_hook()
            return x if x else default

    else:
        return reader()
Пример #2
0
 def defaulter():
     """define default behavior startup"""
     if _readline_available:
         readline.insert_text(default)
     readline.set_startup_hook(defaulter)
     readline.get_completer()
     readline.set_completer(completer)
Пример #3
0
def getinput(question, default="", reader=raw_input, completer=None, width=_defaultwidth):  # pragma: no cover
    """
    http://stackoverflow.com/questions/2617057/\
            supply-inputs-to-python-unittests
    """
    if reader == raw_input:
        if not _readline_available:
            val = raw_input(question.ljust(width))
            if val:
                return val
            else:
                return default
        else:

            def defaulter():
                """define default behavior startup"""
                readline.insert_text(default)

            if _readline_available:
                readline.set_startup_hook(defaulter)
                readline.get_completer()
                readline.set_completer(completer)

            x = raw_input(question.ljust(width))

            if _readline_available:
                readline.set_startup_hook()
            return x if x else default

    else:
        return reader()
Пример #4
0
 def set_readline_completer(self):
     if readline.get_completer() != self.complete:  # pylint: disable=comparison-with-callable
         readline.parse_and_bind("tab: complete")
         self._backup_completer = readline.get_completer()
         readline.set_completer(self.complete)
         if self.completer_delims is not None:
             readline.set_completer_delims(self.completer_delims)
Пример #5
0
    def test_context_manager_with_unmocked_readline(self):
        from certbot.display import completer
        reload_module(completer)

        original_completer = readline.get_completer()
        original_delims = readline.get_completer_delims()

        with completer.Completer():
            pass

        self.assertEqual(readline.get_completer(), original_completer)
        self.assertEqual(readline.get_completer_delims(), original_delims)
Пример #6
0
    def test_context_manager_with_unmocked_readline(self):
        from letsencrypt.display import completer
        reload_module(completer)

        original_completer = readline.get_completer()
        original_delims = readline.get_completer_delims()

        with completer.Completer():
            pass

        self.assertEqual(readline.get_completer(), original_completer)
        self.assertEqual(readline.get_completer_delims(), original_delims)
Пример #7
0
 def test_path_completer(self):
     self.fpc.activate()
     self.assertEqual(readline.get_completer(), path_completer)
     self.assert_expected_output("test_d", ['test_dir' + os.sep])
     self.assert_expected_output(
         "test_dir" + os.sep, [os.path.join("test_dir", "a_file"),
                               os.path.join("test_dir", "b_file")])
     self.assert_expected_output(
         os.path.join("test_dir", "a"), [os.path.join("test_dir", "a_file")])
     self.assert_expected_output("c_fi", ["c_file"])
     self.fpc.deactivate()
     self.assertEqual(readline.get_completer(), None)
Пример #8
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey + ": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write("%s\n" % self.intro)
            self._stopping = False
            success = True
            while not self._stopping:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            line = input(self.prompt)
                        except EOFError:
                            line = "EOF"
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not line:
                            line = "EOF"
                        else:
                            line = line.rstrip("\r\n")
                line = self.precmd(line)
                try:
                    success = self.onecmd(line)
                except (CommandSyntaxError, InvalidNodeError, LockError) as err:
                    # Note that here we do not attempt to catch all ZeekControl
                    # exceptions; letting some just terminate the program to
                    # avoid getting in an unknown state (e.g. error while
                    # reloading the config).
                    success = False
                    print("Error: %s" % err)
                self.postcmd(False, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
        return success
Пример #9
0
    def loop(self):
        previous_completer = readline.get_completer()
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.walk)
        prompt = self.prompt + self.prompt_delim
        if not ishell._current_prompt:
            previous_prompt = prompt
        else:
            previous_prompt = ishell._current_prompt
        ishell._current_prompt = prompt
        if self.welcome_message:
            sys.stdout.write(self.welcome_message + "\n\r")
        while 1:
            try:
                sys.stdout.write("\r")
                if self._exit:
                    break
                sys.stdout.write("\033[K")
                input_ = input(prompt + " ")
                if not input_.strip():
                    self.print_childs_help()
                elif input_ in ('quit', 'exit'):
                    break
                else:
                    self.walk_and_run(input_)
            except (KeyboardInterrupt, EOFError):
                print("exit")
                break

            except Exception:
                print(traceback.format_exc())
                sys.exit(1)

        ishell._current_prompt = previous_prompt
        readline.set_completer(previous_completer)
Пример #10
0
 def run_interactive(self):
     '''
     Starts interactive CLI mode.
     '''
     history = self.prefs['path_history']
     index = self.prefs['path_history_index']
     if history and index:
         if index < len(history):
             try:
                 target = self._root_node.get_node(history[index])
             except ValueError:
                 self._current_node = self._root_node
             else:
                 self._current_node = target
     try:
         old_completer = readline.get_completer()
         self._cli_loop()
     except KeyboardInterrupt:
         self.con.raw_write('\n')
         self.run_interactive()
     except Exception:
         self.log.exception()
         self.run_interactive()
     finally:
         readline.set_completer(old_completer)
Пример #11
0
def execute_interactive():
    """ Runs the command mode once, reading the standard input for a command
    and executing it. Will return execution once a command has been executed
    or if an invalid command was passed.
    """
    old_completer = readline.get_completer()
    readline.set_completer(__readline_completer)
    readline.parse_and_bind('tab: complete')

    term.enter_buffer()
    # default raw mode is not readline friendly.
    # restore after saving display, for restoring is destructive
    term.restore_tty()

    try:
        cmd_name = raw_input('REACH:')
    except:
        # return to raw_mode
        term.set_raw()
        readline.set_completer(old_completer)
        term.leave_buffer()
        return

    cmd_args = [x for x in cmd_name.split(' ') if x != '']
    if cmd_args and cmd_args[0] in registry:
        try:
            registry[cmd_args[0]][1](cmd_args)
        except Exception, e:
            print(e)
            term.pause()
Пример #12
0
    def run(self):

        # Preserve existing history
        if self.preserve_history:
            old_history = [readline.get_history_item(index) for index in xrange(readline.get_current_history_length())]
            old_history = filter(lambda x: x is not None, old_history)
            readline.clear_history()
            map(readline.add_history, self.history)

        old_completer = readline.get_completer()
        readline.set_completer(self.complete)
        readline.parse_and_bind("bind ^I rl_complete")

        while True:
            cmdline = raw_input("%s > " % (self.prefix,))
            self.last_wd_complete = ("", ())
            if not cmdline:
                continue

            # Try to dispatch command
            try:
                self.execute(cmdline)
            except SystemExit, e:
                print "Exiting shell: %s" % (e.code,)
                break
            except UnknownCommand, e:
                print "Command '%s' unknown." % (e,)
Пример #13
0
    def __init__(self, board: Board):
        self.board = board
        self.colour = AnsiColour()
        self.prompt = self.base_prompt
        self.prompt_fmt = ('{bold-cyan}{id} {yellow}{platform}'
                           ' ({free}){bold-blue}{pwd}> ')
        self.multi_cmd_mode = False
        self.prompt_colour = 'yellow'  # Colour of the short prompt
        self.alias: Dict[str, str] = {}  # Command aliases
        self.params: Dict[str, Any] = {}  # Params we can use in prompt
        self.names: Dict[str, str] = {}  # Map device unique_ids to names
        self.lsspec: Dict[str, str] = {}  # Extra colour specs for %ls
        readline.set_completer_delims(' \t\n>;')

        # Cmd.cmdloop() overrides completion settings in ~/.inputrc
        # We can disable this by setting completekey=''
        super().__init__(completekey='')
        # But then we need to load the completer function ourselves
        self.old_completer = readline.get_completer()
        readline.set_completer(self.complete)  # type: ignore

        # Load the readline history file
        self.history_file = os.path.expanduser(HISTORY_FILE)
        if os.path.isfile(self.history_file):
            readline.read_history_file(self.history_file)
Пример #14
0
    def loop(self):
        previous_completer = readline.get_completer()
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.walk)
        prompt = self.prompt + self.prompt_delim
        if not ishell._current_prompt:
            previous_prompt = prompt
        else:
            previous_prompt = ishell._current_prompt
        ishell._current_prompt = prompt
        while 1:
            try:
                sys.stdout.write("\r")
                if self._exit:
                    break
                input_ = raw_input(prompt + " ")
                if not input_:
                    self.help()
                elif input_ in ('quit', 'exit'):
                    break
                else:
                    self.walk_and_run(input_)

            except Exception, e:
                print "Error: %s" % e
                sys.exit(1)
Пример #15
0
    def cmdloop(self):
        """
        Issue a prompt, parse input and dispatch to the corresponding method.
        """
        self.old_completer = readline.get_completer()  # save the old completer
        readline.set_completer(self.complete)
        readline.parse_and_bind(self.completekey + ": complete")  # set the autocomplete key for readline.
        readline.set_completer_delims(readline.get_completer_delims().replace('-', ''))  # remove "-" because options
        readline.set_completion_display_matches_hook(self.rl_display_hook)  # set our display hook
        # read history file if exists
        historyfile = self.config.getfile("gat", "historyfile", True)
        readline.read_history_file(historyfile)

        try:
            # print the intro after startup, if config entry show_intro is True.
            if self.config.getboolean("gat", "show_intro"):
                self.stdout.write(str(self.intro) + "\n")
            stop = None
            while not stop:
                if self.cmdqueue:  # TODO: check if we still need that.
                    line = self.cmdqueue.pop(0)
                else:
                    try:
                        line = raw_input(self.prompt)
                    except EOFError:
                        line = 'EOF'
                stop = self.handle_cmd(line)
            self.postloop()  # we are done, execute the post loop method.
        except KeyboardInterrupt:
            self.stdout.write("\nPlease use quit to exit the framework. Exiting now.\n")
            self.postloop()
        finally:
            readline.set_completer(self.old_completer)
            readline.write_history_file(historyfile)
Пример #16
0
 def backup_completer(self):
     try:
         self.old_completer = readline.get_completer()
         readline.set_completer(self.complete)
         readline.parse_and_bind("{0}: complete".format(self.complete_key))
     except ImportError:
         ConsoleError('couldn\'t put new completer')
Пример #17
0
 def run(self, args):
     try:
         if not self.client.conn.modules["os.path"].exists(
                 "C:\\WIndows\\system32\\Packet.dll"):
             raise PupyModuleError(
                 "WinPcap is not installed !. You should download/upload NPcap (https://github.com/nmap/npcap/releases) and install it silently (with the /S flag) "
             )
         if not self.client.conn.modules[
                 'ctypes'].windll.Shell32.IsUserAnAdmin():
             self.warning(
                 "you are running this module without beeing admin")
         with redirected_stdo(self.client.conn):
             old_completer = readline.get_completer()
             try:
                 psc = self.client.conn.modules[
                     'pyshell.controller'].PyShellController()
                 readline.set_completer(psc.get_completer())
                 readline.parse_and_bind('tab: complete')
                 psc.write("from scapy.all import *")
                 while True:
                     cmd = raw_input(">>> ")
                     psc.write(cmd)
             finally:
                 readline.set_completer(old_completer)
                 readline.parse_and_bind('tab: complete')
     except KeyboardInterrupt:
         pass
Пример #18
0
def _get_bip39_firstwords():
    readline.parse_and_bind("tab: complete")
    old_completer = readline.get_completer()
    completer = WordCompleter(wordlist=BIP39)
    readline.set_completer(completer.complete)
    while True:
        fw = input(
            blue_fg("Enter the first 23 words of your BIP39 seed phrase: ")
        ).strip()
        fw_num = len(fw.split())

        if fw_num not in (11, 14, 17, 20, 23):
            # TODO: 11, 14, 17, or 20 word seed phrases also work but this is not documented as it's for advanced users
            print_red(
                f"You entered {fw_num} words. "
                "We recommend 23 words, but advanced users may enter 11, 14, 17 or 20 words."
            )
            continue

        all_words_valid = True
        for cnt, word in enumerate(fw.split()):
            if word not in BIP39:
                print_red(f"Word #{cnt+1} `{word}` is not a valid BIP39 word")
                all_words_valid = False
        if all_words_valid is False:
            continue

        readline.set_completer(old_completer)
        return fw
Пример #19
0
def rlinput(prompt, prefill='', oneline=False, ctxkey=''):
    """
    Get user input with readline editing support.
    """

    sentinel = ''
    if prefill is None:
        prefill = ''
    
    def only_once(text):
        """ generator for startup hook """
        readline.insert_text(text)
        yield
        while True:
            yield

    savedhist = NamedTemporaryFile()
    readline.write_history_file(savedhist.name)
    ctxhistname = ".tl" + ctxkey + "history"
    ctxhistfile = os.path.join(G.ProjectFolder, ctxhistname)
    try:
        readline.clear_history()
    except AttributeError:
        print "This readline doesn't support clear_history()"
        raise
    
    savedcompleter = readline.get_completer()
    try:
        ulines = uniqify(ctxhistfile)
        readline.read_history_file(ctxhistfile)
        readline.set_completer(HistoryCompleter(ulines).complete)
    except IOError:
        pass

    readline.parse_and_bind('tab: complete')
    saveddelims = readline.get_completer_delims()
    readline.set_completer_delims('') ## No delims. Complete entire lines.
    readline.set_completion_display_matches_hook(match_display_hook)
    gen = only_once(prefill)
    readline.set_startup_hook(gen.next)
    try:
        if oneline:
            edited = raw_input(prompt)
        else:
            print prompt
            edited = "\n".join(iter(raw_input, sentinel))

        if edited.endswith(r'%%'):
            ## Invoke external editor
            edited = external_edit(edited[0:-2])
        return edited
    finally:
        ## Restore readline state 
        readline.write_history_file(ctxhistfile)
        readline.clear_history()
        readline.read_history_file(savedhist.name)
        savedhist.close()
        readline.set_completer(savedcompleter)
        readline.set_completer_delims(saveddelims)
        readline.set_startup_hook()    
Пример #20
0
    def loop(self):
        previous_completer = readline.get_completer()
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.walk)
        prompt = self.prompt + self.prompt_delim
        if not ishell._current_prompt:
            previous_prompt = prompt
        else:
            previous_prompt = ishell._current_prompt
        ishell._current_prompt = prompt
        if self.welcome_message:
            sys.stdout.write(self.welcome_message + "\n\r")
        while 1:
            try:
                sys.stdout.write("\r")
                if self._exit:
                    break
                sys.stdout.write("\033[K")
                input_ = input(prompt + " ")
                if not input_.strip():
                    self.print_childs_help()
                elif input_ in ('quit', 'exit'):
                    break
                else:
                    self.walk_and_run(input_)
            except (KeyboardInterrupt, EOFError):
                print("exit")
                break

            except Exception:
                print(traceback.format_exc())
                sys.exit(1)

        ishell._current_prompt = previous_prompt
        readline.set_completer(previous_completer)
Пример #21
0
    def cmdloop(self, intro=None):
        self.old_completer = readline.get_completer()
        self.old_completer_delims = readline.get_completer_delims()
        readline.set_completer(self.complete)
        readline.parse_and_bind(self.completekey + ": complete")
        readline.parse_and_bind("set bell-style none")
        readline.parse_and_bind("set show-all-if-ambiguous")
        readline.parse_and_bind("set completion-query-items -1")

        # If press help key, add the character and accept the line
        readline.parse_and_bind('"?": "\C-q?\C-j"')
        # Register a function for execute before read user
        # input. We can use it for insert text at command line
        readline.set_pre_input_hook(self.pre_input_hook)
        readline.set_completer_delims(' \t\n')

        try:
            stop = None
            while not stop:
                try:
                    line = raw_input(self.prompt)
                except EOFError:
                    line = 'EOF'

                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
        finally:
            readline.set_completer(self.old_completer)
            readline.set_completer_delims(self.old_completer_delims)
Пример #22
0
    def run(self, line):
        def _formatOutput(res):
            if isinstance(res, str):
                return res
            else:
                try:
                    return "\n".join(_formatOutput(r) for r in res)
                except TypeError:
                    return str(res)

        ishellCompleter = readline.get_completer()
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(completer.complete)

        filePath = raw_input(
            "Please specify a path to the output file: ").strip()

        readline.set_completer(ishellCompleter)
        if os.path.isfile(filePath):
            confirm = raw_input(
                "File already exists and will be overwritten, confirm? [y/N] ")
            if confirm is "" or confirm[0] not in ("y", "Y"):
                print "Canceled."
                return

        with open(filePath, "w+") as handle:
            handle.write(_formatOutput(feathermodules.results))
Пример #23
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.
        """

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)

                if 'libedit' in readline.__doc__:
                    # readline linked to BSD libedit
                    if self.completekey == 'tab':
                        key = '^I'
                    else:
                        key = self.completekey
                    readline.parse_and_bind('bind %s rl_complete' % (key, ))
                else:
                    # readline linked to the real readline
                    readline.parse_and_bind(self.completekey + ': complete')

            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro) + "\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            line = input(self.prompt)
                        except EOFError:
                            line = 'EOF'
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = 'EOF'
                        else:
                            line = line.rstrip('\r\n')
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
Пример #24
0
def do(server, handler, config, args):
    orig_exit = builtins.exit
    orig_quit = builtins.quit

    def disabled_exit(*args, **kwargs):
        handler.display(
            Error('exit() disabled ! use ctrl+D to exit the python shell'))

    builtins.exit = disabled_exit
    builtins.quit = disabled_exit
    oldcompleter = readline.get_completer()

    try:
        local_ns = {
            'server': server,
            'handler': handler,
            'config': config,
        }

        readline.set_completer(PythonCompleter(local_ns=local_ns).complete)
        readline.parse_and_bind('tab: complete')
        code.interact(local=local_ns)

    except Exception as e:
        handler.display(Error(e))

    finally:
        readline.set_completer(oldcompleter)
        readline.parse_and_bind('tab: complete')
        builtins.exit = orig_exit
        builtins.quit = orig_quit
Пример #25
0
    def cmdloop(self, intro=None):
        self.old_completer = readline.get_completer()
        self.old_completer_delims = readline.get_completer_delims()
        readline.set_completer(self.complete)
        readline.parse_and_bind(self.completekey+": complete")
        readline.parse_and_bind("set bell-style none")
        readline.parse_and_bind("set show-all-if-ambiguous")
        readline.parse_and_bind("set completion-query-items -1")

        # If press help key, add the character and accept the line
        readline.parse_and_bind('"?": "\C-q?\C-j"')
        # Register a function for execute before read user
        # input. We can use it for insert text at command line
        readline.set_pre_input_hook(self.pre_input_hook)
        readline.set_completer_delims(' \t\n')

        try:
            stop = None
            while not stop:
                try:
                    line = raw_input(self.prompt)
                except EOFError:
                    line = 'EOF'

                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
        finally:
            readline.set_completer(self.old_completer)
            readline.set_completer_delims(self.old_completer_delims)
Пример #26
0
    def loop(self) -> None:
        """
        Main loop

        """

        self.old_completer = readline.get_completer()

        line = input(self.prompt)
        job_status = r'.*Status:.*(FINISHED|ABORTED|EXCEPTION)'

        if re.match(r'.*\|*monitor', line):
            if not line.startswith('show '):
                print('Can only monitor show commands.')
            else:
                while True:
                    line = line.partition('|')[0].rstrip()
                    try:
                        print(chr(27) + "[2J")
                        output = self.execute(line)
                        output += '\n\nHit Ctrl+C to abort'
                        print(output)

                        if re.findall(job_status, output):
                            print('Job is not running, stopping monitor.')
                            break

                        time.sleep(2)
                    except KeyboardInterrupt:
                        break
        else:
            print(self.execute(line), end='')

        readline.set_completer(self.old_completer)
        readline.write_history_file('history.txt')
Пример #27
0
    def collect(self, parent_name=None):
        """Depth first collection of tree
        """
        # Do we have data to collect?
        if parent_name == None:
            # We are the top tag!
            self.collection['tag'] = [self.name]

        if self.parse != None:
            self.col_old_completer = readline.get_completer()
            readline.set_completer(self.complete)
            readline.set_completer_delims('\n\r\t;')
            readline.parse_and_bind("tab: complete")

            if self.notes:
                print self.notes
            res = self._get_in(parent_name)

            if parent_name:
                ekey = parent_name + '_' + self.name
            else:
                ekey = self.name

            self.collection.update({ekey: res})
            
            readline.set_completer(self.col_old_completer)

        for child in self.descendants:
            child.collect(self.name)
Пример #28
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey + ": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write("%s\n" % self.intro)
            self._stopping = False
            success = True
            while not self._stopping:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            line = py3bro.input(self.prompt)
                        except EOFError:
                            line = "EOF"
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not line:
                            line = "EOF"
                        else:
                            line = line.rstrip("\r\n")
                line = self.precmd(line)
                try:
                    success = self.onecmd(line)
                except (CommandSyntaxError, InvalidNodeError, LockError) as err:
                    # Note that here we do not attempt to catch all BroControl
                    # exceptions; letting some just terminate the program to
                    # avoid getting in an unknown state (e.g. error while
                    # reloading the config).
                    success = False
                    print("Error: %s" % err)
                self.postcmd(False, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
        return success
Пример #29
0
 def interact(self, cmd=None):
     _reset_readline()
     if cmd and isinstance(cmd, BaseCommands):
         self.push_command(cmd)
     if readline:
         oc = readline.get_completer()
         readline.set_completer(self._rl_completer)
     try:
         try:
             while 1:
                 ui = self._cmd._ui
                 try:
                     line = ui.user_input()
                     if not line:
                         continue
                     while self.feed(line + "\n"):
                         line = ui.more_user_input()
                 except EOFError:
                     self._cmd._print()
                     self.pop_command()
         except (CommandQuit, CommandExit):  # last command does this
             pass
     finally:
         if readline:
             readline.set_completer(oc)
             if self._historyfile:
                 try:
                     readline.write_history_file(self._historyfile)
                 except:
                     pass
Пример #30
0
    def __get_user_port(self, type):
        old_completer = readline.get_completer()

        ports = []
        for port in serial.tools.list_ports.comports():
            ports.append(port[0])

        compl_ports = Completer(ports)
        readline.set_completer_delims('\t')
        readline.parse_and_bind('tab: complete')
        readline.set_completer(compl_ports.list_completer)

        port = None
        while port is None:
            port = input(f'{Fore.YELLOW}{type} port:{Fore.RESET} ').strip()
            if port in ['q', 'exit']:
                return
            elif port not in ports:
                error(f'Port {port} is not valid.')
                warning('Valid ports:')
                for port in ports:
                    warning('\t' + port)
                warning('Type \'exit\' to return.')
                port = None

        readline.set_completer(old_completer)
        return port
Пример #31
0
    def run(self):

        # Preserve existing history
        if self.preserve_history:
            old_history = [
                readline.get_history_item(index)
                for index in xrange(readline.get_current_history_length())
            ]
            old_history = filter(lambda x: x is not None, old_history)
            readline.clear_history()
            map(readline.add_history, self.history)

        old_completer = readline.get_completer()
        readline.set_completer(self.complete)
        readline.parse_and_bind("bind ^I rl_complete")

        while True:
            cmdline = raw_input("%s > " % (self.prefix, ))
            self.last_wd_complete = ("", ())
            if not cmdline:
                continue

            # Try to dispatch command
            try:
                self.execute(cmdline)
            except SystemExit, e:
                print "Exiting shell: %s" % (e.code, )
                break
            except UnknownCommand, e:
                print "Command '%s' unknown." % (e, )
Пример #32
0
    def __enter__(self):
        # we only do something if we have readline
        if not haveReadline:
            return self
        ## Set up the new history context
        self.historyFile = os.path.join(os.getenv('HOME'),
                                        ".{0}.history".format(self.basename))
        (h, self.oldhistFile) = tempfile.mkstemp(prefix=self.basename,
                                                 suffix=".hist",
                                                 dir="/tmp")
        # only need the filename, really
        os.close(h)
        readline.write_history_file(self.oldhistFile)
        readline.clear_history()

        # if reading the old history fails, fail silently
        # (the file might not exist yet)
        try:
            readline.read_history_file(self.historyFile)
        except:
            pass

        # store the old completer, install our own one
        readline.parse_and_bind("tab: complete")
        #readline.parse_and_bind("C-c: backward-kill-line")
        self.oldCompleter = readline.get_completer()
        readline.set_completer(self.completer)
        return self
Пример #33
0
def edit_attr(dict, attr):
    """Edits an attribute in the dictionary dict."""
    completer = readline.get_completer()
    readline.set_completer(None)
    current_value = dict[attr]
    try:
        print("\n# Documentation: %s" % dict[attr + "_doc"])
    except:
        pass

    print("# Current value: %s = %s" % (attr, str(current_value)))

    while True:
        new_value = eval(input("#     New value: %s = " % attr))

        if new_value == "":
            new_value = current_value
            print("# Using the current value (%s)" % str(current_value))
            break

        try:
            new_value = double(new_value)  # try interpreting as a number
        except:
            pass  # leave as a string

        break

    readline.set_completer(completer)
    return new_value
Пример #34
0
def sftp_cmd(*args):
    sftp = Channel.get_instance().get_transport().open_sftp_client()

    old_completer = readline.get_completer()
    readline.set_completer(sftp_completer(sftp))
    old_delim = readline.get_completer_delims()
    readline.set_completer_delims(' /')
    global rcwd

    try:
        try:
            cmd = raw_input('SFTP> ')
        except EOFError:
            return
        except KeyboardInterrupt:
            return
        while not cmd or not 'quit'.startswith(cmd):
            args = [x for x in cmd.split(' ') if x]
            if args and args[0] in all_cmd:
                all_cmd[args[0]](sftp, args)
            else:
                print('invalid command')
            try:
                cmd = raw_input('SFTP> ')
            except EOFError:
                return
            except KeyboardInterrupt:
                return
    finally:
        readline.set_completer(old_completer)
        readline.set_completer_delims(old_delim)
Пример #35
0
    def wrapper(*args, **kwargs):
        try:
            import readline
            handle_readline = True
        except ImportError:
            handle_readline = False

        if handle_readline:
            # backup & reset readline completer
            old_readline_completer = readline.get_completer()
            readline.set_completer((lambda x: x))
            # backup & reset readline history
            old_readline_history = []
            hist_sz = readline.get_current_history_length()
            for i in range(1, hist_sz + 1):
                line = readline.get_history_item(i)
                old_readline_history.append(line)
            readline.clear_history()

        try:
            retval = function(*args, **kwargs)
        finally:

            if handle_readline:
                # restore old readline completer
                readline.set_completer(old_readline_completer)
                # restore old readline history
                readline.clear_history()
                for line in old_readline_history:
                    readline.add_history(line)

        return retval
Пример #36
0
    def loop(self):
        previous_completer = readline.get_completer()
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.walk)
        prompt = self.prompt + self.prompt_delim
        if not ishell._current_prompt:
            previous_prompt = prompt
        else:
            previous_prompt = ishell._current_prompt
        ishell._current_prompt = prompt
        while 1:
            try:
                sys.stdout.write("\r")
                if self._exit:
                    break
                input_ = raw_input(prompt + " ")
                if not input_:
                    self.help()
                elif input_ in ('quit', 'exit'):
                    break
                else:
                    self.walk_and_run(input_)

            except Exception, e:
                print "Error: %s" % e
                sys.exit(1)
Пример #37
0
 def _wpl(text):
     _t = text
     completer = readline.get_completer()
     try:
         import bdb
         inst = completer.__self__
         if isinstance(inst, bdb.Bdb):
             import pdb
             if hasattr(pdb, "GLOBAL_PDB"):  # pdb++
                 cls = pdb.Completer
                 assert cls.__module__ == "fancycompleter"
                 if not hasattr(cls, "__PYTHON_EL_orig"):
                     # Original drops common path, only lists leaves
                     cls.__PYTHON_EL_orig = cls.attr_matches  # not restored
                     import rlcompleter
                     cls.attr_matches = rlcompleter.Completer.attr_matches
             elif (isinstance(inst, pdb.Pdb)  # quacks vanilla, so add patch
                   and hasattr(pdb, "cmd")
                   and completer.__func__ is pdb.cmd.Cmd.complete
                   and "complete" not in inst.__dict__):
                 inst.complete = _complete.__get__(inst)
             elif not hasattr(inst._completions):
                 raise RuntimeError("Unsupported PDB: {}".format(
                     inst.__class__))
             inst.complete(text, 0)
             return inst._completions[:]
         return orig(text)
     except Exception:
         readline.set_completer(completer)
         return orig(_t)
Пример #38
0
 def run_interactive(self):
     '''
     Starts interactive CLI mode.
     '''
     history = self.prefs['path_history']
     index = self.prefs['path_history_index']
     if history and index:
         if index < len(history):
             try:
                 target = self._root_node.get_node(history[index])
             except ValueError:
                 self._current_node = self._root_node
             else:
                 self._current_node = target
     try:
         old_completer = readline.get_completer()
         self._cli_loop()
     except KeyboardInterrupt:
         self.con.raw_write('\n')
         self.run_interactive()
     except Exception:
         self.log.exception()
         self.run_interactive()
     finally:
         readline.set_completer(old_completer)
Пример #39
0
        def cmdloop(self, intro=None):
            """Repeatedly issue a prompt, accept input, parse an initial prefix
            off the received input, and dispatch to action methods, passing them
            the remainder of the line as argument.
            """

            self.preloop()
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    self.old_completer = readline.get_completer()
                    readline.set_completer(self.complete)

                    if 'libedit' in readline.__doc__:
                        # readline linked to BSD libedit
                        if self.completekey == 'tab':
                            key = '^I'
                        else:
                            key = self.completekey
                        readline.parse_and_bind('bind %s rl_complete' % (key,))
                    else:
                        # readline linked to the real readline
                        readline.parse_and_bind(self.completekey + ': complete')

                except ImportError:
                    pass
            try:
                if intro is not None:
                    self.intro = intro
                if self.intro:
                    self.stdout.write(str(self.intro)+"\n")
                stop = None
                while not stop:
                    if self.cmdqueue:
                        line = self.cmdqueue.pop(0)
                    else:
                        if self.use_rawinput:
                            try:
                                line = input(self.prompt)
                            except EOFError:
                                line = 'EOF'
                        else:
                            self.stdout.write(self.prompt)
                            self.stdout.flush()
                            line = self.stdin.readline()
                            if not len(line):
                                line = 'EOF'
                            else:
                                line = line.rstrip('\r\n')
                    line = self.precmd(line)
                    stop = self.onecmd(line)
                    stop = self.postcmd(stop, line)
                self.postloop()
            finally:
                if self.use_rawinput and self.completekey:
                    try:
                        import readline
                        readline.set_completer(self.old_completer)
                    except ImportError:
                        pass
Пример #40
0
    def wrapper(*args, **kwargs):
        try:
            import readline
            handle_readline = True
        except ImportError:
            handle_readline = False

        if handle_readline:
            # backup & reset readline completer
            old_readline_completer = readline.get_completer()
            readline.set_completer((lambda x: x))
            # backup & reset readline history
            old_readline_history = []
            hist_sz = readline.get_current_history_length()
            for i in range(1, hist_sz + 1):
                line = readline.get_history_item(i)
                old_readline_history.append(line)
            readline.clear_history()

        try:
            retval = function(*args, **kwargs)
        finally:

            if handle_readline:
                # restore old readline completer
                readline.set_completer(old_readline_completer)
                # restore old readline history
                readline.clear_history()
                for line in old_readline_history:
                    readline.add_history(line)

        return retval
Пример #41
0
   def run(self, line):
      def _formatOutput(res):
         if isinstance(res, str):
            return res
         else:
             try:
                 return "\n".join(_formatOutput(r) for r in res)
             except TypeError:
                 return str(res)

      ishellCompleter = readline.get_completer()
      readline.set_completer_delims(' \t\n;')
      readline.parse_and_bind("tab: complete")
      readline.set_completer(completer.complete)

      filePath =  raw_input("Please specify a path to the output file: ").strip()

      readline.set_completer(ishellCompleter)
      if os.path.isfile(filePath):
         confirm = raw_input("File already exists and will be overwritten, confirm? [y/N] ")
         if confirm is "" or confirm[0] not in ("y", "Y"):
            print "Canceled."
            return

      with open(filePath, "w+") as handle:
        handle.write(_formatOutput(feathermodules.results))
Пример #42
0
    def __get_user_rate(self, type, port):
        old_completer = readline.get_completer()

        rates = []
        for rate in Connection.BAUDRATES:
            rates.append(str(rate))

        compl_rates = Completer(rates)
        readline.set_completer(compl_rates.list_completer)
        rate = None
        while rate is None:
            rate = input(f'{Fore.YELLOW}{type} rate:{Fore.RESET} ').strip()
            if rate in ['q', 'exit']:
                break
            elif rate == '':
                rate = Connection.get_baudrate(port)
            elif rate not in rates:
                error(f'Rate {rate} is not valid.')
                warning('Valid baudrates:')
                for rate in rates:
                    warning('\t' + rate)
                warning('Type \'exit\' to return.')
                rate = None
            else:
                rate = int(rate)

        readline.set_completer(old_completer)
        return rate
Пример #43
0
def edit_attr(dict, attr):
    """Edits an attribute in the dictionary dict."""
    completer = readline.get_completer()
    readline.set_completer(None)
    current_value = dict[attr]
    try:
        print "\n# Documentation: %s" % dict[attr + "_doc"]
    except:
        pass

    print "# Current value: %s = %s" % (attr, str(current_value))

    while True:
        new_value = raw_input("#     New value: %s = " % attr)

        if new_value == "":
            new_value = current_value
            print "# Using the current value (%s)" % str(current_value)
            break

        try:
            new_value = double(new_value) # try interpreting as a number
        except:
            pass                # leave as a string

        break

    readline.set_completer(completer)
    return new_value
Пример #44
0
 def interact(self, cmd=None):
     _reset_readline()
     if cmd and isinstance(cmd, BaseCommands):
         self.push_command(cmd)
     if readline:
         oc = readline.get_completer()
         readline.set_completer(self._rl_completer)
     try:
         try:
             while 1:
                 ui = self._cmd._ui
                 try:
                     line = ui.user_input()
                     if not line:
                         continue
                     while self.feed(line+"\n"):
                         line = ui.more_user_input()
                 except EOFError:
                     self._cmd._print()
                     self.pop_command()
         except (CommandQuit, CommandExit): # last command does this
             pass
     finally:
         if readline:
             readline.set_completer(oc)
             if self._historyfile:
                 try:
                     readline.write_history_file(self._historyfile)
                 except:
                     pass
Пример #45
0
 def readline_complete(self, text):
     i = 0
     while True:
         res = readline.get_completer()(text, i)
         if not res: break
         yield res
         i += 1
Пример #46
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """

        import readline
        readline.clear_history()
        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey + ": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro) + "\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            line = raw_input(self.prompt)
                        except EOFError:
                            line = 'EOF'
                        except KeyboardInterrupt:
                            line = '\r\n'
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = 'EOF'
                        else:
                            line = line.rstrip('\r\n')
                self.cleartimer()
                self.mytimer(CLI_TIMEOUT_SECONDS)
                if any(x in line for x in banned_characters):
                    print u'错误的命令'.encode("utf-8")
                else:
                    line = self.precmd(line)
                    stop = self.onecmd(line)
                    stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
Пример #47
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """
        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline

                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey + ": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro) + "\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    to = select.select([sys.stdin], [], [], 1)[0]
                    if self.terminated:
                        return
                    if not to:
                        continue
                    if self.use_rawinput:
                        try:
                            try:
                                line = raw_input(self.prompt)  # python2
                            except NameError:
                                line = input(self.prompt)  # python3
                        except EOFError:
                            line = "EOF"
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = "EOF"
                        else:
                            line = line.rstrip("\r\n")
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline

                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
Пример #48
0
    def cmdloop(self, intro=None):

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                readline.read_history_file(self.conf['history_file'])
                readline.set_history_length(self.conf['history_size'])
            except IOError:
                # if history file does not exist
                try:
                    open(self.conf['history_file'], 'w').close()
                    readline.read_history_file(self.conf['history_file'])
                except IOError:
                    pass
            self.old_completer = readline.get_completer()
            readline.set_completer(self.complete)
            readline.parse_and_bind(self.completekey+": complete")
        try:
            if intro is not None:
                self.intro = intro
            if self.conf['intro']:
                self.stdout.write(str(self.conf['intro'])+"\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            line = raw_input(self.prompt)
                        except EOFError:
                            line = 'EOF'
                        except KeyboardInterrupt:
                            self.stdout.write('\n')
                            line = ''

                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = 'EOF'
                        else:
                            line = line[:-1] # chop \n
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
            try:
                readline.write_history_file(self.conf['history_file'])
            except IOError:
                self.log.error('WARN: couldn\'t write history '                \
                                   'to file %s\n' % self.conf['history_file'])
Пример #49
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """
        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline

                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey + ": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro) + "\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    to = select.select([sys.stdin], [], [], 1)[0]
                    if self.terminated:
                        return
                    if not to:
                        continue
                    if self.use_rawinput:
                        try:
                            try:
                                line = raw_input(self.prompt)  # python2
                            except NameError:
                                line = input(self.prompt)  # python3
                        except EOFError:
                            line = "EOF"
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = "EOF"
                        else:
                            line = line.rstrip("\r\n")
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline

                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
Пример #50
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey + ": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro) + "\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            if sys.version_info.major == 2:
                                line = raw_input(self.prompt)
                            else:
                                self.stdout.write(self.prompt)
                                self.stdout.flush()
                                line = self.stdin.readline()
                                if not len(line):
                                    line = 'EOF'
                                else:
                                    line = line.rstrip('\r\n')
                        except EOFError:
                            line = 'EOF'
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = 'EOF'
                        else:
                            line = line.rstrip('\r\n')
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
Пример #51
0
 def __enter__(self):
     self.old_completer = readline.get_completer()
     try:
         if self.histfile:
             readline.read_history_file(self.histfile)
     except IOError:  # the first time
         pass
     return self
Пример #52
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.
        """
        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey+": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro)+"\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0) 
                    self.stdout.write( "pop" )

                else:
                    if self.use_rawinput:
                        try:
                            line = raw_input(self.prompt)
                        except EOFError:
                            line = 'EOF'
                            #self.stdout.write("exception")
                    else:
                        if line != 'EOF':
                            self.stdout.write(self.prompt)
                            self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = 'EOF'
                        else:
                            line = line.rstrip('\r\n')
                #if line != 'EOF':
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
                    #self.stdout.write(line)
                #time.sleep(3)

            self.postloop()

        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
Пример #53
0
 def __init__(self,
              env,
              path_from_home=None,
              prompt_method=None,
              path_delimeter=None,
              stdin=None,
              stdout=None,
              stderr=None,
              logger=None,
              add_setup_menu=False):
     # Note super does not work as Cmd() is an 'old style' class which
     # does not inherit from object(). Instead call init directly.
     #self._submenu_names = None
     self._last_keyboard_interupt = 0
     signal.signal(signal.SIGINT, self._keyboard_interupt_handler)
     if 'colorama' in sys.modules:
         init()
     self.stdout = stdout or env.default_output or sys.stdout
     self.stdin = stdin or env.default_input or sys.stdin
     # Attempt to populate the command history from history file,
     # if it has not yet, and the file is provided and exists
     try:
         history_len = readline.get_history_length()
         if history_len < 1:
             history_path = getattr(env.simplecli_config, 'history_file', None)
             if history_path and os.path.exists(history_path):
                 readline.read_history_file(history_path)
     except ImportError as IE:
         self.eprint('Failed to read in history file, err:{0}'.format(IE))
         pass
     Cmd.__init__(self, completekey='tab', stdin=stdin, stdout=stdout)
     self.stderr = stderr or env.default_error or sys.stderr
     if not self.name:
         raise ValueError('Class must define "name", extend BaseEnv')
     assert isinstance(env, BaseEnv), "env variable must be of type BaseEnv"
     self._add_setup_menu = add_setup_menu
     # Env should be of type BaseEnv or None
     self.env = env
     # Use the shared env logger if provided for ease of controlling log levels, etc.
     self.logger = logger
     if not self.logger and hasattr(self.env, 'logger'):
         self.logger = self.env.logger
     # Setup CLI interface
     #if self.env and self.env.home is None:
     #    print('({0}): setting self for env.home:"{1}"'.format(self, self.env.home))
     #    self.env.home = self
     #    readline.set_completion_display_matches_hook(self._completer_display)
     self.callers = []
     self.prompt_method = prompt_method or env.simplecli_config.prompt_method
     self.path_delimeter = path_delimeter or env.simplecli_config.path_delimeter
     self._path_from_home = []
     self.path_from_home = path_from_home
     self._setup()
     self._init_submenus()
     self._old_completer = readline.get_completer()
     if self.env and not self.env.get_cached_menu_by_class(self.__class__):
         self.env.menu_cache.append(self)
Пример #54
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.parse_and_bind(self.completekey + ": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write("%s\n" % self.intro)
            self._stopping = False
            success = True
            while not self._stopping:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            line = py3bro.input(self.prompt)
                        except EOFError:
                            line = "EOF"
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not line:
                            line = "EOF"
                        else:
                            line = line.rstrip("\r\n")
                line = self.precmd(line)
                try:
                    success = self.onecmd(line)
                except Exception as e:
                    success = False
                    print("Error: %s" % e)
                self.postcmd(False, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass
        return success
Пример #55
0
    def run(self, shell):
        self.old_completer = readline.get_completer()
        readline.set_completer(self.complete)
        print(
            title_str("Entering " + self.name + " Wizard", width=shell.width, box=True, align='center'),
            '\n',
            self.description, '\n\n',
            word_wrap(
                "To exit, enter either Ctrl+C, Ctrl+D, or 'quit'. For help "
                "about the current step, enter 'help' or '?'.", shell.width
            ),
            sep=''
        )

        running = True
        for step in self.steps:
            self.active_step = step
            valid = False
            while not valid:
                raw = None
                prompt = step.name
                if step.default is not None:
                    d = step.default
                    if callable(d):
                        d = d(self.values)
                    prompt += ' [{}]'.format(d)
                prompt += ': '
                try:
                    raw = input(prompt)
                except (KeyboardInterrupt, EOFError):
                    print()
                    print(AnsiStdout.red, "Wizard canceled", AnsiStdout.reset, sep='')
                    readline.set_completer(self.old_completer)
                    return None

                if raw.lower() == 'quit':
                    print(AnsiStdout.red, "Exiting wizard", AnsiStdout.reset, sep='')
                    readline.set_completer(self.old_completer)
                    return None
                elif raw.lower() in ('?', 'help'):
                    print(word_wrap(step.help, shell.width))
                else:
                    if not raw and step.default is not None:
                        raw = step.default

                    try:
                        value = step.validate(self.values, raw)
                    except ValueError as e:
                        print(AnsiStdout.red, "Error: ", str(e), AnsiStdout.reset, sep='')
                        print(AnsiStdout.yellow, step.name, ": ", step.help, sep='')
                    else:
                        self.values[step.id] = value
                        valid = True

        readline.set_completer(self.old_completer)
        return self.values
 def __enter__(self):
     # store the old values
     self.cmpl_function = readline.get_completer()
     self.delims = readline.get_completer_delims()
     # no completion delimiters
     readline.set_completer_delims('')
     # this class works as completer
     readline.set_completer(self)
     # tab completes
     readline.parse_and_bind('tab: complete')
Пример #57
0
def rl_set_completer(completer):
    """Context manager to temporarily replace the readline completer"""
    if rlmodule is not None:
        _COMPLETER_STACK.append(rlmodule.get_completer())
        rlmodule.set_completer(completer)
    try:
        yield
    finally:
        if rlmodule is not None:
            rlmodule.set_completer(_COMPLETER_STACK.pop(-1))
Пример #58
0
    def preloop(self):
        # load a new completer, save the old
        self.old_completer = readline.get_completer()
        readline.set_completer(self.Completer.complete)

        # sane defaults
        readline.parse_and_bind("tab: complete")
        readline.parse_and_bind("set show-all-if-ambiguous on")

        self._mate()
Пример #59
0
Файл: cmd.py Проект: 1ee7/pydbgp
 def preloop(self):
     """Hook method executed once when the cmdloop() method is called."""
     if self.completekey:
         try:
             import readline
             self.old_completer = readline.get_completer()
             readline.set_completer(self.complete)
             readline.parse_and_bind(self.completekey+": complete")
         except ImportError:
             pass
Пример #60
0
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.

        """

        self.preloop()
        if self.use_rawinput and self.completekey:
            try:
                import readline
                self.old_completer = readline.get_completer()
                readline.set_completer(self.complete)
                readline.set_completer_delims(" ")
                readline.parse_and_bind(self.completekey+": complete")
            except ImportError:
                pass
        try:
            if intro is not None:
                self.intro = intro
            if self.intro:
                self.stdout.write(str(self.intro)+"\n")
            stop = None
            while not stop:
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    if self.use_rawinput:
                        try:
                            line = raw_input(self.prompt)
                        except KeyboardInterrupt:
                            print
                            line = ""
                        except EOFError:
                            print
                            line = '.quit'
                    else:
                        self.stdout.write(self.prompt)
                        self.stdout.flush()
                        line = self.stdin.readline()
                        if not len(line):
                            line = '.quit'
                        else:
                            line = line[:-1] # chop \n
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            self.postloop()
        finally:
            if self.use_rawinput and self.completekey:
                try:
                    import readline
                    readline.set_completer(self.old_completer)
                except ImportError:
                    pass