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)
示例#2
0
文件: cli.py 项目: Juniper/OpenClos
 def set_completion_display_matches_hook ( self, function ):
     if util.isPlatformWindows ():
         import pyreadline
         Readline ().set_completion_display_matches_hook ( function )
     else:
         import readline
         readline.set_completion_display_matches_hook ( function )
示例#3
0
def _setup_autocompletion(bot):
    def completer(text, state):
        if text.startswith('@'):
            users = (user[u'name'] for user in bot.users.itervalues())
            matched = [user for user in users if user.startswith(text[1:])]
        elif text.startswith('#'):
            matched = [
                channel for channel in bot.get_channel_names()
                if channel.startswith(text[1:])
            ]
        else:
            return None
        try:
            return u"{}{} ".format(text[0], matched[state])
        except KeyError:
            return None

    def show_matches(substitution, matches, longest_match_length):
        with autoflush(bot):
            print(' '.join(matches))

    readline.set_completer_delims(' \t\n;')
    readline.set_completer(completer)
    if 'libedit' in readline.__doc__:
        readline.parse_and_bind("bind ^I rl_complete")
    else:
        readline.parse_and_bind("tab: complete")
    readline.set_completion_display_matches_hook(show_matches)
示例#4
0
 def set_completion_display_matches_hook(self, function):
     if util.isPlatformWindows():
         import pyreadline
         Readline().set_completion_display_matches_hook(function)
     else:
         import readline
         readline.set_completion_display_matches_hook(function)
示例#5
0
def create_client():
    completer = PathCompleter()
    readline.set_completer_delims(' \t\n;')
    readline.set_completer(completer.complete)
    readline.parse_and_bind('tab: complete')
    readline.set_completion_display_matches_hook(completer.display_matches)
    print('Enter a client database name\n\t')
    db_path = input("> ")
    db_extension = '.pickle'
    if not os.path.exists(db_path):
        if not db_path.endswith(db_extension):
            db_path += db_extension
        print('New database will be created at {}'.format(db_path))
        clients = []
    else:
        print('Read database from {}'.format(db_path))
        clients = utils.load_clients(db_path)
    
    client_name = input('Nom client: ')
    new_client = client.Client(client_name)
    print(new_client.name)
    utils.append_client_to_db(clients, new_client)
    print(' '.join(['{}:{}'.format(c.id_, c.name) for c in clients]))
    # == "
    # == "# save client list
    utils.save_clients(clients,  db_path)
示例#6
0
    def __init__(self, options):
        """
        Constructor
        """
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.complete)
        readline.set_completion_display_matches_hook(self.completer_print)
        try:
            readline.read_history_file(CLI_HISTORY)
        except IOError:
            pass
        readline.set_history_length(CLI_MAX_CMD_HISTORY)

        if not os.path.isdir(CLI_RESULT_HISTORY_FOLDER):
            os.system('rm -rf %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER))
            os.system('mkdir -p %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER))

        try:
            self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True)
        except:
            os.system('rm -rf %s' % CLI_RESULT_HISTORY_KEY)
            self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True)
            print "\nRead history file: %s error. Has recreate it.\n" % CLI_RESULT_HISTORY_KEY

        self.start_key = 'start_key'
        self.last_key = 'last_key'
        self.cli_cmd_func = {'help': self.show_help,
                             'history': self.show_help,
                             'more': self.show_more,
                             'quit': sys.exit,
                             'exit': sys.exit,
                             'save': self.save_json_to_file}
        self.cli_cmd = self.cli_cmd_func.keys()

        self.raw_words_db = self._parse_api_name(inventory.api_names)
        self.words_db = list(self.raw_words_db)
        self.words_db.extend(self.cli_cmd)
        self.words = list(self.words_db)
        self.is_cmd = False
        self.curr_pattern = None
        self.matching_words = None
        self.api_class_params = {}
        self.build_api_parameters()
        self.api = None
        self.account_name = None
        self.user_name = None
        self.session_uuid = None
        if os.path.exists(SESSION_FILE):
            try:
                with open(SESSION_FILE, 'r') as session_file_reader:
                    self.session_uuid = session_file_reader.readline().rstrip()
                    self.account_name = session_file_reader.readline().rstrip()
                    self.user_name = session_file_reader.readline().rstrip()
            except EOFError:
                pass

        self.hostname = options.host
        self.port = options.port
        self.no_secure = options.no_secure
        self.api = api.Api(host=self.hostname, port=self.port)
示例#7
0
    def __init__(self, url: Optional[str] = '',
                 prompt: Optional[str] = 'CNaaS# ',
                 model: Optional[str] = 'cnaas.yml',
                 token: Optional[str] = None,
                 banner: Optional[str] = '') -> None:
        """
        Constructur.

        Init CliParser and do some other stuff.

        Returns:

        """

        if os.path.isfile('history.txt'):
            readline.read_history_file('history.txt')

        self.url = url
        self.token = token
        self.prompt = prompt
        self.cli = CliParser(model)
        self.builtin = ['no', 'show', 'help', 'history', 'quit', 'update']
        self.modifiers = ['|']
        self.modifiers_commands = ['grep', 'monitor']

        readline.set_completer(self.complete)
        readline.parse_and_bind('tab: complete')
        readline.parse_and_bind('?: complete')
        readline.parse_and_bind('"\\C-l": clear-screen')
        readline.set_completion_display_matches_hook(self.print_suggestions)

        if banner != '':
            print(banner)
示例#8
0
    def complete(self, text, state):
        """Return the next possible completion for 'text'.
        If a command has not been entered, then complete against command list.
        Otherwise try to call complete_<command> to get list of completions.
        """
        try:
            self.dprint('{0}.complete(text="{1}", state="{2}")'.format(
                self.name, text, state))
            origline = readline.get_line_buffer() or ""
            try:
                if state == 0:
                    line = origline.lstrip()
                    stripped = len(origline) - len(line)
                    begidx = readline.get_begidx() - stripped
                    endidx = readline.get_endidx() - stripped

                    menu = self.get_submenu_completer_for_text(origline)
                    readline.set_completion_display_matches_hook(
                        menu._completer_display)
                    self.dprint(
                        'Complete(): text:{0}, origline:{1}, begidx:{2}, endidz:{3}'
                        .format(text, line, begidx, endidx))
                    if begidx >= 0:
                        #cmd, args, foo = self.parseline(line)
                        cmd, args, foo = menu.parseline(text)
                        compfunc = menu.completedefault

                        if cmd and hasattr(
                                menu,
                                'complete_' + cmd,
                        ):
                            compfunc = getattr(menu, 'complete_' + cmd)
                            menu.dprint('Complete(): got method complete_' +
                                        str(cmd))
                    else:
                        menu.dprint('Complete(): non-zero state sending to '
                                    'completenames(), state:{0}'.format(state))
                        compfunc = menu.completenames
                    try:
                        self.completion_matches = compfunc(
                            text, line, begidx, endidx)
                    except:
                        print_exc()
                        raise
                try:
                    self.dprint(
                        'Returning {0}.complete(text={1}, state={2}) = "{3}"'.
                        format(self.name, text, state,
                               self.completion_matches[state]))
                    return self.completion_matches[state]
                except IndexError:
                    return None
            finally:
                readline.set_completion_display_matches_hook(
                    self._completer_display)
        except Exception as E:
            # readline will often fail silently, and not always show/raise errors
            self.stderr.write('{0}\nError in complete: "{1}"'.format(
                get_traceback(), E))
            raise
示例#9
0
    def __init__(self, options):
        """
        Constructor
        """
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.complete)
        readline.set_completion_display_matches_hook(self.completer_print)
        try:
            readline.read_history_file(CLI_HISTORY)
        except IOError:
            pass
        readline.set_history_length(CLI_MAX_CMD_HISTORY)

        if not os.path.isdir(CLI_RESULT_HISTORY_FOLDER):
            os.system('rm -rf %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER))
            os.system('mkdir -p %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER))

        try:
            self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True)
        except:
            os.system('rm -rf %s' % CLI_RESULT_HISTORY_KEY)
            self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True)
            print "\nRead history file: %s error. Has recreate it.\n" % CLI_RESULT_HISTORY_KEY

        self.start_key = 'start_key'
        self.last_key = 'last_key'
        self.cli_cmd_func = {'help': self.show_help,
                             'history': self.show_help,
                             'more': self.show_more,
                             'quit': sys.exit,
                             'exit': sys.exit,
                             'save': self.save_json_to_file}
        self.cli_cmd = self.cli_cmd_func.keys()

        self.raw_words_db = self._parse_api_name(inventory.api_names)
        self.words_db = list(self.raw_words_db)
        self.words_db.extend(self.cli_cmd)
        self.words = list(self.words_db)
        self.is_cmd = False
        self.curr_pattern = None
        self.matching_words = None
        self.api_class_params = {}
        self.build_api_parameters()
        self.api = None
        self.account_name = None
        self.user_name = None
        self.session_uuid = None
        if os.path.exists(SESSION_FILE):
            session_file_reader = open(SESSION_FILE, 'r')
            self.session_uuid = session_file_reader.readline().rstrip()
            try:
                self.account_name = session_file_reader.readline().rstrip()
                self.user_name = session_file_reader.readline().rstrip()
            except EOFError:
                pass

        self.hostname = options.host
        self.port = options.port
        self.no_secure = options.no_secure
        self.api = api.Api(host=self.hostname, port=self.port)
示例#10
0
 def _set_readline_display_matches(self):
     '''
     In order to stay compatible with python versions < 2.6,
     we are not using readline.set_completion_display_matches_hook() but
     instead use ctypes there to bind to the C readline hook if needed.
     This hooks a callback function to display readline completions.
     '''
     if 'set_completion_display_matches_hook' in dir(readline):
         readline.set_completion_display_matches_hook(
             self._display_completions_python)
     else:
         from ctypes import cdll, CFUNCTYPE, POINTER
         from ctypes import c_char_p, c_int, c_void_p, cast
         libreadline = None
         try:
             libreadline = cdll.LoadLibrary('libreadline.so')
         except OSError:
             try:
                 libreadline = cdll.LoadLibrary('libreadline.so.5')
             except OSError:
                 try:
                     libreadline = cdll.LoadLibrary('libreadline.so.6')
                 except OSError:
                     self.log.critical(
                         "Could not find readline shared library.")
         if libreadline:
             completion_func_type = \
                     CFUNCTYPE(None, POINTER(c_char_p), c_int, c_int)
             hook = completion_func_type(self._display_completions)
             ptr = c_void_p.in_dll(libreadline,
                                   'rl_completion_display_matches_hook')
             ptr.value = cast(hook, c_void_p).value
示例#11
0
    def prompt_for_input(self, input_key):
        if input_key not in self.autocomplete_entries:
            self.autocomplete_entries[input_key] = []

        existing_entries = self.autocomplete_entries[input_key]

        completer = Completer(existing_entries)
        readline.set_completer_delims(' \t\n;')
        readline.set_completer(completer.complete)
        readline.parse_and_bind('tab: complete')
        readline.set_completion_display_matches_hook(completer.display_matches)

        input_value = input("\n" + input_key + ": ").strip()

        if input_value == "s":
            return None

        if input_value and input_value not in existing_entries:
            self.autocomplete_entries[input_key] += [input_value]
            if input_key in self.autocomplete_files:
                with open(self.autocomplete_files[input_key], "a") as file:
                    file.write(input_value)
                    file.write("\n")

        return input_value
示例#12
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()    
示例#13
0
    def postcmd(self, stop, line):
        # overwrite the logger facility to remove the current prompt and append
        # a new one
        self._log_handler.set_prompt_mode(self.prompt)

        # restore any completion display hook we might have set
        readline.set_completion_display_matches_hook()
        return stop
示例#14
0
    def _enableAutocompletion(self):
        '''
		This method enables the autocompletion mode.
		'''
        readline.set_completer_delims(';\t')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self._autocompletion)
        readline.set_completion_display_matches_hook(self._matchDisplayHook)
示例#15
0
文件: core.py 项目: pisua/yblues
 def set_display_hook(display_hook, prompt, session, context):
     try:
         readline.set_completion_display_matches_hook(
             lambda sub, matches, longest: display_hook(
                 prompt, session, context, matches, longest))
     except AttributeError:
         # Display hook not available
         pass
示例#16
0
文件: iface.py 项目: wlaub/pybld
    def __init__(self, g):
        import readline
        self.g = g
        self.ac = AutoCompleter(self.g)
        readline.set_completer(self.ac.complete)
        readline.set_completion_display_matches_hook(self.ac.showMatches)
        readline.parse_and_bind('tab: complete')

        self.infile = sys.stdin
示例#17
0
文件: core.py 项目: tcalmant/ipopo
 def set_display_hook(display_hook, prompt, session, context):
     try:
         readline.set_completion_display_matches_hook(
             lambda sub, matches, longest: display_hook(
                 prompt, session, context, matches, longest
             )
         )
     except AttributeError:
         # Display hook not available
         pass
示例#18
0
文件: squires.py 项目: google/squires
  def _ReadlinePrepare(self):
    """Prepare readline for use."""
    readline.set_completion_display_matches_hook(
        self.root.FormatCompleterOptions)
    readline.set_completer(self.root.ReadlineCompleter)
    readline.parse_and_bind('tab: complete')
    readline.parse_and_bind('?: possible-completions')
    readline.set_completer_delims(' \t')

    self._old_delims = readline.get_completer_delims()
    readline.set_completer_delims(' ')
示例#19
0
文件: gclone.py 项目: rostegg/gclone
def main():
    print()
    print("[+] Available repositories for %s%s%s:\n" %
          (Colors.OKBLUE, current_user, Colors.ENDC))
    print('\t' + '\n\t'.join('%s%s%s' % (Colors.BOLD, item, Colors.ENDC)
                             for item in autocomple_dic))
    completer = RepositoriesCompleter(autocomple_dic)
    readline.set_completer_delims(' \t\n;')
    readline.set_completer(completer.complete)
    readline.parse_and_bind('tab: complete')
    readline.set_completion_display_matches_hook(completer.display_matches)
    enter_repository()
示例#20
0
    def complete_fetch(self, text, line, begidx, endidx):

        def draw_timestamp(substitution, matches, longest_match_length):
            print()

            for drawing in matches:
                # we underline the current matching, because it makes easier to
                # visually go through the list
                display_drawing = f'\033[4m{drawing[:len(substitution)]}\033[0m{drawing[len(substitution):]}'

                try:
                    t = time.localtime(int(drawing))
                    t = time.strftime('%Y-%m-%d at %H:%M', t)
                    print(f'{display_drawing}: drawn on the {t}')
                except ValueError:
                    # 'all' case
                    print(f'{display_drawing}{":":<8} fetch all drawings')

            print(self.prompt, readline.get_line_buffer(), sep='', end='')
            sys.stdout.flush()

        # mark the end of the line so we can match on the number of fields
        if line.endswith(' '):
            line += 'm'
        fields = line.split()

        completion = []
        if len(fields) == 2:
            for device in self._manager.devices:
                if device.address.startswith(text.upper()):
                    completion.append(device.address)

        elif len(fields) == 3:
            readline.set_completion_display_matches_hook(draw_timestamp)
            device = None
            for d in self._manager.devices:
                if d.address == fields[1]:
                    device = d
                    break

            if device is None:
                return

            timestamps = [str(t) for t in d.drawings_available]
            timestamps.append('all')

            for t in timestamps:
                if t.startswith(text.lower()):
                    completion.append(t)

        return completion
示例#21
0
 def __init__(self, stdout=None):
     self.ipdb = IPDB()
     self.ptr = self.ipdb
     self.ptrname = None
     self.stack = []
     self.matches = []
     self.isatty = sys.stdin.isatty()
     self.prompt = ''
     self.stdout = stdout or sys.stdout
     self.set_prompt()
     code.InteractiveConsole.__init__(self)
     readline.parse_and_bind('tab: complete')
     readline.set_completer(self.completer)
     readline.set_completion_display_matches_hook(self.display)
示例#22
0
    def _init_rline(self):
        log.d("Init GNU readline")

        # [GNU] readline config
        rl_load()

        # TAB: autocomplete
        readline.parse_and_bind("tab: complete")
        # readline.parse_and_bind("set show-all-if-ambiguous on")
        # readline.parse_and_bind("set show-all-if-unmodified on")
        # readline.parse_and_bind("set menu-complete-display-prefix on")
        # readline.parse_and_bind("tab: complete")

        # Show 'show all possibilities' if there are too many items
        readline.parse_and_bind("set completion-query-items 50")
        readline.parse_and_bind("set completion-ignore-case on")
        readline.parse_and_bind("set echo-control-characters off")

        # Remove '-' from the delimiters for handle suggestions
        # starting with '-' properly and '/' for handle paths
        # `~!@#$%^&*()-=+[{]}\|;:'",<>/?
        # readline.set_completer_delims(multireplace(readline.get_completer_delims(),
        #                                      [("-", ""), ("/", "")]))

        # Completion function
        readline.set_completer(self._next_suggestion)

        # Use only a space as word breaker
        readline.set_completer_delims(" ")

        # Use a custom render function; this has been necessary for print
        # colors while using rline for the suggestions engine
        if has_gnureadline():
            readline.set_completion_display_matches_hook(
                self._display_suggestions_gnureadline)
        elif has_pyreadline():
            readline.rl.mode._display_completions = self._display_suggestions_pyreadline

        # Set quote characters for quoting strings with spaces
        rl_set_completer_quote_characters('"')

        rl_set_char_is_quoted_p(self._quote_detector)

        # History
        try:
            readline.set_auto_history(False)
            self._load_history()
        except:
            log.w("History not supported")
            pass
示例#23
0
    def __init__(self, options):
        '''
        Constructor
        '''
        readline.parse_and_bind("tab: complete")
        readline.set_completer(self.complete)
        readline.set_completion_display_matches_hook(self.completer_print)
        try:
            readline.read_history_file(CLI_HISTORY)
        except IOError:
            pass
        readline.set_history_length(CLI_MAX_CMD_HISTORY)

        if not os.path.isdir(CLI_RESULT_HISTORY_FOLDER):
            os.system('rm -rf %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER))
            os.system('mkdir -p %s' % os.path.dirname(CLI_RESULT_HISTORY_FOLDER))

        try:
            self.hd = filedb.FileDB(CLI_RESULT_HISTORY_KEY, is_abs_path=True)
        except:
            print "Read history file: %s error, please manually delete it." % CLI_RESULT_HISTORY_KEY
            return

        self.start_key = 'start_key'
        self.last_key = 'last_key'
        self.cli_cmd_func = {'help': self.show_help, \
                'history':  self.show_help, \
                'more':     self.show_more, \
                'quit':     sys.exit, \
                'exit':     sys.exit, \
                'save':     self.save_json_to_file}
        self.cli_cmd = self.cli_cmd_func.keys()

        self.raw_words_db = self._parse_api_name(inventory.api_names)
        self.words_db = list(self.raw_words_db)
        self.words_db.extend(self.cli_cmd)
        self.words = list(self.words_db)
        self.is_cmd = False
        self.curr_pattern = None
        self.matching_words = None
        self.api_class_params = {}
        self.build_api_parameters()
        self.api = None
        self.session_uuid = None
        if os.path.exists(SESSION_FILE):
            self.session_uuid = open(SESSION_FILE, 'r').readline()

        self.hostname = options.host
        self.port = options.port
        self.api = api.Api(host=self.hostname, port=self.port)
示例#24
0
 def __init__(self, stdout=None, log=None, sources=None):
     global HAS_READLINE
     self.db = NDB(log=log, sources=sources)
     self.db.config = {'show_format': 'json'}
     self.stdout = stdout or sys.stdout
     self.session = Session(self.db, self.stdout, self.set_prompt)
     self.matches = []
     self.isatty = sys.stdin.isatty()
     self.prompt = ''
     self.set_prompt()
     code.InteractiveConsole.__init__(self)
     if HAS_READLINE:
         readline.parse_and_bind('tab: complete')
         readline.set_completer(self.completer)
         readline.set_completion_display_matches_hook(self.display)
示例#25
0
 def __init__(self, stdout=None, log=None, sources=None):
     global HAS_READLINE
     self.db = NDB(log=log, sources=sources)
     self.db.config = {'show_format': 'json'}
     self.stdout = stdout or sys.stdout
     self.session = Session(self.db, self.stdout, self.set_prompt)
     self.matches = []
     self.isatty = sys.stdin.isatty()
     self.prompt = ''
     self.set_prompt()
     code.InteractiveConsole.__init__(self)
     if HAS_READLINE:
         readline.parse_and_bind('tab: complete')
         readline.set_completer(self.completer)
         readline.set_completion_display_matches_hook(self.display)
示例#26
0
def setup_readline():
    """Initialize the readline module."""
    # Edited to work with pyenv
    histpath = os.path.join(os.path.expanduser("~"), ".pyenv", "versions",
                            sys.version.split(' ')[0] , "share")

    if sys.version[0] == '2':
        histfile = os.path.join(histpath, "py2hist")
    else:
        histfile = os.path.join(histpath, "py3hist")
    if not os.path.exists(histpath):
        os.mkdir(histpath)
    atexit.register(readline.write_history_file, histfile)
    try:
        readline.read_history_file(histfile)
    except IOError:
        pass
    # Complete with the tab key. M-tab completes on local file names.
    readline.parse_and_bind("tab: complete")
    # readline indentation keybinding
    # Control-j: indent 4 spaces
    # Control-u: unindent 4 spaces
    # First, create some dummy shortcuts:
    # Add four spaces:
    readline.parse_and_bind(r'"\M-j": "    "')
    # Delete four characters (behind point):
    readline.parse_and_bind(r'"\M-h": delete-char')
    readline.parse_and_bind(r'"\M-k": "\M-h\M-h\M-h\M-h"')
    # Move point forward four characters:
    readline.parse_and_bind(r'"\M-e": "\C-f\C-f\C-f\C-f"')
    # Move point backward four characters:
    readline.parse_and_bind(r'"\M-g": "\C-b\C-b\C-b\C-b"')
    # Second, define another set-mark shortcut, since it only seems to
    # work when bound to a letter key.
    readline.parse_and_bind(r'"\M-\C-j": set-mark')
    # C-j macro: set mark, go to the beginning of the line, add four
    # spaces, exchange point and mark, and then move forward four
    # characters to the same point in the text where you were before,
    # regardless of the new indentation.
    readline.parse_and_bind(r'"\C-j": "\M-\C-j\C-a\M-j\C-x\C-x\M-e"')
    # C-u macro: Move back four characters, set mark, move to the
    # beginning of the line, move forward four characters, delete four
    # characters, then exchange mark and point. This would be shorter
    # readline.parse_and_bind(r'"\C-u": "\M-g\M-\C-j\C-a\M-e\M-k\C-x\C-x"')
    readline.parse_and_bind(r'"\C-u": "\M-g\M-\C-j\C-a\M-k\C-x\C-x"')
    # load readline history
    readline.set_pre_input_hook(rl_autoindent)
    readline.set_completion_display_matches_hook(comp_disp_matches)
示例#27
0
    def complete(self, text, state):
        """Return the next possible completion for 'text'.
        If a command has not been entered, then complete against command list.
        Otherwise try to call complete_<command> to get list of completions.
        """
        try:
            self.dprint('{0}.complete(text="{1}", state="{2}")'.format(self.name, text, state))
            origline = readline.get_line_buffer() or ""
            try:
                if state == 0:
                    line = origline.lstrip()
                    stripped = len(origline) - len(line)
                    begidx = readline.get_begidx() - stripped
                    endidx = readline.get_endidx() - stripped

                    menu = self.get_submenu_completer_for_text(origline)
                    readline.set_completion_display_matches_hook(menu._completer_display)
                    self.dprint('Complete(): text:{0}, origline:{1}, begidx:{2}, endidz:{3}'
                                .format(text, line, begidx, endidx))
                    if begidx>=0:
                        #cmd, args, foo = self.parseline(line)
                        cmd, args, foo = menu.parseline(text)
                        compfunc = menu.completedefault

                        if cmd and hasattr(menu, 'complete_' + cmd,):
                            compfunc = getattr(menu, 'complete_' + cmd)
                            menu.dprint('Complete(): got method complete_' + str(cmd))
                    else:
                        menu.dprint('Complete(): non-zero state sending to '
                                    'completenames(), state:{0}'.format(state))
                        compfunc = menu.completenames
                    try:
                        self.completion_matches = compfunc(text, line, begidx, endidx)
                    except:
                        print_exc()
                        raise
                try:
                    self.dprint('Returning {0}.complete(text={1}, state={2}) = "{3}"'
                                .format(self.name, text, state, self.completion_matches[state]))
                    return self.completion_matches[state]
                except IndexError:
                    return None
            finally:
                readline.set_completion_display_matches_hook(self._completer_display)
        except Exception as E:
            # readline will often fail silently, and not always show/raise errors
            self.stderr.write('{0}\nError in complete: "{1}"'.format(get_traceback(), E))
            raise
示例#28
0
def setup_readline():
    """Initialize the readline module."""
    # Edited to work with pyenv
    histpath = os.path.join(os.path.expanduser("~"), ".pyenv", "versions",
                            sys.version.split(' ')[0], "share")

    if sys.version[0] == '2':
        histfile = os.path.join(histpath, "py2hist")
    else:
        histfile = os.path.join(histpath, "py3hist")
    if not os.path.exists(histpath):
        os.mkdir(histpath)
    atexit.register(readline.write_history_file, histfile)
    try:
        readline.read_history_file(histfile)
    except IOError:
        pass
    # Complete with the tab key. M-tab completes on local file names.
    readline.parse_and_bind("tab: complete")
    # readline indentation keybinding
    # Control-j: indent 4 spaces
    # Control-u: unindent 4 spaces
    # First, create some dummy shortcuts:
    # Add four spaces:
    readline.parse_and_bind(r'"\M-j": "    "')
    # Delete four characters (behind point):
    readline.parse_and_bind(r'"\M-h": delete-char')
    readline.parse_and_bind(r'"\M-k": "\M-h\M-h\M-h\M-h"')
    # Move point forward four characters:
    readline.parse_and_bind(r'"\M-e": "\C-f\C-f\C-f\C-f"')
    # Move point backward four characters:
    readline.parse_and_bind(r'"\M-g": "\C-b\C-b\C-b\C-b"')
    # Second, define another set-mark shortcut, since it only seems to
    # work when bound to a letter key.
    readline.parse_and_bind(r'"\M-\C-j": set-mark')
    # C-j macro: set mark, go to the beginning of the line, add four
    # spaces, exchange point and mark, and then move forward four
    # characters to the same point in the text where you were before,
    # regardless of the new indentation.
    readline.parse_and_bind(r'"\C-j": "\M-\C-j\C-a\M-j\C-x\C-x\M-e"')
    # C-u macro: Move back four characters, set mark, move to the
    # beginning of the line, move forward four characters, delete four
    # characters, then exchange mark and point. This would be shorter
    # readline.parse_and_bind(r'"\C-u": "\M-g\M-\C-j\C-a\M-e\M-k\C-x\C-x"')
    readline.parse_and_bind(r'"\C-u": "\M-g\M-\C-j\C-a\M-k\C-x\C-x"')
    # load readline history
    readline.set_pre_input_hook(rl_autoindent)
    readline.set_completion_display_matches_hook(comp_disp_matches)
示例#29
0
文件: console.py 项目: skizap/RTC2
def start_shell(cmd_handler):
    commands = cmd_handler.commands
    completer = Autocomplete(list(set(commands)))
    readline.set_completer_delims('\t')
    readline.set_completer(completer.complete)
    readline.parse_and_bind('tab: complete')
    readline.set_completion_display_matches_hook(completer.display_matches)
    while True:
        cmd = input("> ")
        try:
            res = cmd_handler.handle(cmd)
        except Exception as e:
            print("Error: " + str(e))
            res = None
        if res == "exit":
            break
示例#30
0
def startShell():
    #build possible inputs:
    possibleInputs = ['modules', 'cls', 'clear', 'quit', 'exit', 'help']
    for m in modules:
        possibleInputs.append(m)

    if autocomplete is True:
        completer = AutoCompleter(
            list(set(possibleInputs)),
            "\n" + Fore.LIGHTCYAN_EX + "pyd> " + Style.RESET_ALL)
        readline.set_completer_delims(' \t\n;')
        readline.set_completer(completer.complete)
        readline.parse_and_bind('tab: complete')
        readline.set_completion_display_matches_hook(completer.display_matches)
    cmd = input("\n" + Fore.LIGHTCYAN_EX + "pyd> " + Style.RESET_ALL)
    handleCommand(cmd)
示例#31
0
 def __init__(self, stdout=None):
     global HAS_READLINE
     self.ipdb = IPDB()
     self.ptr = self.ipdb
     self.ptrname = None
     self.stack = []
     self.matches = []
     self.isatty = sys.stdin.isatty()
     self.prompt = ''
     self.stdout = stdout or sys.stdout
     self.set_prompt()
     code.InteractiveConsole.__init__(self)
     if HAS_READLINE:
         readline.parse_and_bind('tab: complete')
         readline.set_completer(self.completer)
         readline.set_completion_display_matches_hook(self.display)
示例#32
0
    def __enter__(self) -> 'PathCompleter':
        import readline

        from .dircolors import Dircolors
        if 'libedit' in readline.__doc__:
            readline.parse_and_bind("bind -e")
            readline.parse_and_bind("bind '\t' rl_complete")
        else:
            readline.parse_and_bind('tab: complete')
            readline.parse_and_bind('set colored-stats on')
            readline.set_completer_delims(
                ' \t\n`!@#$%^&*()-=+[{]}\\|;:\'",<>?')
        readline.set_completion_display_matches_hook(self.format_completions)
        self.original_completer = readline.get_completer()
        readline.set_completer(self)
        self.cache: Dict[str, Tuple[str, ...]] = {}
        self.dircolors = Dircolors()
        return self
示例#33
0
def cmdUseShell(modulename):
    possibleInputs = [
        'info', 'generate', 'gen', 'attributes', 'exit', 'quit',
        'set <attribute> <value>', 'help'
    ]

    if autocomplete is True:
        completer = AutoCompleter(
            list(set(possibleInputs)),
            "\n" + Fore.LIGHTCYAN_EX + "pyd> " + Style.RESET_ALL + "(" +
            Fore.LIGHTRED_EX + modulename + Style.RESET_ALL + "): ")
        readline.set_completer_delims(' \t\n;')
        readline.set_completer(completer.complete)
        readline.parse_and_bind('tab: complete')
        readline.set_completion_display_matches_hook(completer.display_matches)
    cmdPay = input("\n" + Fore.LIGHTCYAN_EX + "pyd> " + Style.RESET_ALL + "(" +
                   Fore.LIGHTRED_EX + modulename + Style.RESET_ALL + "): ")
    handleUseCmd(cmdPay, modulename)
示例#34
0
def init():
    register_command("exit", exit)
    register_command("end", end)
    register_command("history", history)
    register_command("connect", connect)
    register_command("disconnect", disconnect)
    register_command("help", help)
    register_command("info", info)
    register_command("show", show)
    register_command("debug", debug)

    readline.set_history_length(1000)
    if os.path.exists(HISTORY_PATH):
        readline.read_history_file(HISTORY_PATH)
    readline.set_history_length(1000)

    readline.set_completer(BufferAwareCompleter.complete)
    readline.set_completion_display_matches_hook(post_complete)
    readline.parse_and_bind('tab: complete')
示例#35
0
    def _load_menu(self, menu, path_from_home=None):
        self.dprint('_load_menu():\n\tmenu:{0}\n\tpath from home:{1}'
                    '\n\tself.path_from_home{2}'.format(
                        menu, path_from_home, self.path_from_home))
        if path_from_home is None:
            path_from_home = self.path_from_home
        if isinstance(menu, BaseMenu):
            self.dprint('_load_menu(): got menu INSTANCE: "{0}"'.format(
                menu.__class__.__name__))
            if self.__class__ == menu.__class__:
                return
            menu.env = self.env

            menu.path_from_home = path_from_home
            menu._init_submenus()
        elif isclass(menu) and issubclass(menu, BaseMenu):
            self.dprint('_load_menu(): got menu CLASS: "{0}"'.format(menu))
            existing_menu = self.env.get_cached_menu_by_class(menu)
            if existing_menu:
                if existing_menu.__class__ == self.__class__:
                    return
                menu = existing_menu
                menu.path_from_home = path_from_home
                menu._init_submenus()
            else:
                self.dprint(
                    '_load_menu():Creating menu instance of class:{0}'.format(
                        menu))
                menu = menu(env=self.env, path_from_home=path_from_home)
                #self.env.menu_cache.append(menu)
        else:
            raise TypeError(
                'Menu must of type BaseMenu, menu:{0}, type:{1}'.format(
                    str(menu), type(menu)))
        self = menu
        readline.set_completer(menu.complete)
        readline.set_completion_display_matches_hook(menu._completer_display)
        self.cmdloop(intro=self.intro)
        self.oprint(
            self._color('BLUE') + "**** {0} MENU ****".format(str(self.name)) +
            "\n")
示例#36
0
def main(argv):
  # Unit test

  readline.set_completer(Callback())
  #readline.set_completer_delims(' ')

  # OK, if we do this, then we get the whole damn line!!!
  # Then we just return the whole damn line completed?
  # Problem : the displayed completions.  Is there an option to strip
  # common prefix?
  readline.set_completer_delims('')

  readline.set_completion_display_matches_hook(Display)


  readline.parse_and_bind('tab: complete')
  while True:
    try:
      x = raw_input('$ ')
    except EOFError:
      print()
      break
    print(x)
示例#37
0
    def __init__(self, config):
        self.config = config

        self.commands = sorted([
            'create', 'import', 'passgen', 'clear', 'help', 'use', 'select',
            'insert', 'remove', 'list', 'changedbpass', 'changedbkey',
            'export', 'version', 'exit'
        ])
        self.commands_usage = {
            'create': 'usage : create [dbname]',
            'import': 'usage : import [dbfile]',
            'passgen': 'usage : passgen [length] [alphabet]',
            'use': 'usage : use [dbname]',
            'select': 'usage : select [service]',
            'insert': 'usage : insert [service] [user]',
            'remove': 'usage : remove [index]',
            'export': 'usage : export [dbfile]'
        }
        self.commands_args_help = {
            'import': {
                1: 'ls'
            },
            'use': {
                1: 'existing_dbs'
            },
            'export': {
                1: 'ls'
            }
        }

        self.cache = []
        self.autocompletion = True
        self.buffer = None
        self.prompt = None
        readline.set_completer(self.autocomplete)
        readline.parse_and_bind('tab: complete')
        readline.set_completion_display_matches_hook(self.displaymatches)
示例#38
0
    def _load_menu(self, menu, path_from_home=None):
        self.dprint('_load_menu():\n\tmenu:{0}\n\tpath from home:{1}'
                    '\n\tself.path_from_home{2}'
                    .format(menu, path_from_home, self.path_from_home))
        if path_from_home is None:
            path_from_home = self.path_from_home
        if isinstance(menu, BaseMenu):
            self.dprint('_load_menu(): got menu INSTANCE: "{0}"'.format(menu.__class__.__name__))
            if self.__class__ == menu.__class__:
                    return
            menu.env = self.env

            menu.path_from_home = path_from_home
            menu._init_submenus()
        elif isclass(menu) and issubclass(menu, BaseMenu):
            self.dprint('_load_menu(): got menu CLASS: "{0}"'.format(menu))
            existing_menu = self.env.get_cached_menu_by_class(menu)
            if existing_menu:
                if existing_menu.__class__ == self.__class__:
                    return
                menu = existing_menu
                menu.path_from_home = path_from_home
                menu._init_submenus()
            else:
                self.dprint('_load_menu():Creating menu instance of class:{0}'.format(menu))
                menu = menu(env=self.env,
                            path_from_home=path_from_home)
                #self.env.menu_cache.append(menu)
        else:
            raise TypeError('Menu must of type BaseMenu, menu:{0}, type:{1}'
                            .format(str(menu), type(menu)))
        self = menu
        readline.set_completer(menu.complete)
        readline.set_completion_display_matches_hook(menu._completer_display)
        self.cmdloop(intro=self.intro)
        self.oprint(self._color('BLUE') + "**** {0} MENU ****"
                    .format(str(self.name)) + "\n")
示例#39
0
文件: state.py 项目: prologic/mio
    def repl(self):
        from .utils import tryimport

        readline = tryimport("readline")

        if readline is not None:
            readline.parse_and_bind("tab: complete")

            completer = Completer(self)
            readline.set_completer_delims("")
            readline.set_completer(completer.complete)
            readline.set_completion_display_matches_hook(completer.display_matches)

        print("mio {0:s}".format(version))

        code = ""
        cont = False

        while True:
            try:
                if cont:
                    self.prompt = ".... "
                else:
                    self.prompt = "mio> "

                code += raw_input(self.prompt)

                if code:
                    if check_parens(code):
                        self.runsource(code)
                        code = ""
                        cont = False
                    else:
                        cont = True
            except EOFError:
                raise SystemExit(0)
示例#40
0
文件: adhocsh.py 项目: 8ware/adhocsh
    completion = opts.completion if opts.completion else path.join(
        BASH_COMPLETION_DIR, command)
    if not path.exists(completion):
        print("Completion file not found: " + completion)
        sys.exit(1)

    shell = AdHocShell(command,
                       completion,
                       compfunc=opts.compfunc,
                       default=opts.default,
                       file_completion=opts.file_completion)
    readline.set_completer_delims(' \t\n;:=')
    readline.set_completer(shell.complete)
    readline.parse_and_bind('tab: complete')
    readline.set_completion_display_matches_hook(shell.display_matches)

    print("Ad-hoc shell for {}.".format(command))
    print("Hit Ctrl-D to leave!")

    # Execute default command once at startup
    if opts.allow_default and opts.default:
        default_command = [shell.command]
        default_command.extend(shell.default_subcommand)
        call(default_command)

    if opts.enable_history:
        shell.load_history()

    while True:
        try:
示例#41
0
                    print("Command not implemented")
                except (socket.error, connection_closed_error):
                    self.ftp.disconnect()
                    print("Connection was closed by the server.")
                except ftp_session.quit_error:
                    print("Goodbye.")
                    break
                #except BaseException:
                #    print("")
                #    break


if (__name__ == '__main__'):

    readline.set_completer(Completer(get_ftp_commands()).complete)
    readline.parse_and_bind('tab: complete')
    completer_delims = readline.get_completer_delims()
    readline.set_completer_delims(completer_delims.replace(' ', ''))
    def dhook(a, b):
        print("\n+++++++++++args=%s" % str(a))
    readline.set_completion_display_matches_hook(dhook)

    cli = FtpCli()
    try:
        cli.proc_cli()
    except (EOFError, KeyboardInterrupt):
        print("")
    except (cli_error):
        pass
    
                buffer = ""
            buffer += match

        if buffer:
            print(buffer)

        print("> ", end="")
        print(line_buffer, end="")
        sys.stdout.flush()


completer = PathCompleter()
readline.set_completer_delims(' \t\n;')
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
readline.set_completion_display_matches_hook(completer.display_matches)
print('Enter a client database name\n\t')
db_path = input("> ")

db_extension = '.pickle'
if not os.path.exists(db_path):
    if not db_path.endswith(db_extension):
        db_path += db_extension
    print('New database will be created at {}'.format(db_path))
    clients = []
else:
    print('Read database from {}'.format(db_path))
    clients = utils.load_clients(db_path)

client_name = input('Nom client: ')
new_client = client.Client(client_name)
示例#43
0
def readline_init():
    """Initialize readline."""
    readline.set_completer_delims('')
    readline.parse_and_bind('tab: complete')
    readline.set_completer(readline_completer)
    readline.set_completion_display_matches_hook(readline_printmatches)
示例#44
0
文件: squires.py 项目: google/squires
 def _ReadlineUnprepare(self):
   """Reset readline."""
   readline.set_completer(None)
   readline.set_completion_display_matches_hook(None)
   readline.set_completer_delims(self._old_delims)
示例#45
0
文件: console.py 项目: tcalmant/ipopo
    def readline_completer(self, text, state):
        """
        A completer for the readline library
        """
        if state == 0:
            # New completion, reset the list of matches and the display hook
            self._readline_matches = []
            try:
                readline.set_completion_display_matches_hook(None)
            except AttributeError:
                pass

            # Get the full line
            full_line = readline.get_line_buffer()
            begin_idx = readline.get_begidx()

            # Parse arguments as best as we can
            try:
                arguments = shlex.split(full_line)
            except ValueError:
                arguments = full_line.split()

            # Extract the command (maybe with its namespace)
            command = arguments.pop(0)

            if begin_idx > 0:
                # We're completing after the command (and maybe some args)
                try:
                    # Find the command
                    ns, command = self._shell.get_ns_command(command)
                except ValueError:
                    # Ambiguous command: ignore
                    return None

                # Use the completer associated to the command, if any
                try:
                    configuration = self._shell.get_command_completers(
                        ns, command
                    )
                    if configuration is not None:
                        self._readline_matches = completion_hints(
                            configuration,
                            self.__get_ps1(),
                            self.__session,
                            self._context,
                            text,
                            arguments,
                        )
                except KeyError:
                    # Unknown command
                    pass

            elif "." in command:
                # Completing the command, and a name space is given
                namespace, prefix = text.split(".", 2)
                commands = self._shell.get_commands(namespace)

                # Filter methods according to the prefix
                self._readline_matches = [
                    "{0}.{1}".format(namespace, command)
                    for command in commands
                    if command.startswith(prefix)
                ]
            else:
                # Completing a command or namespace
                prefix = command

                # Default commands goes first...
                possibilities = [
                    "{0} ".format(command)
                    for command in self._shell.get_commands(None)
                    if command.startswith(prefix)
                ]

                # ... then name spaces
                namespaces = self._shell.get_namespaces()
                possibilities.extend(
                    "{0}.".format(namespace)
                    for namespace in namespaces
                    if namespace.startswith(prefix)
                )

                # ... then commands in those name spaces
                possibilities.extend(
                    "{0} ".format(command)
                    for namespace in namespaces
                    if namespace is not None
                    for command in self._shell.get_commands(namespace)
                    if command.startswith(prefix)
                )

                # Filter methods according to the prefix
                self._readline_matches = possibilities

            if not self._readline_matches:
                return None

            # Return the first possibility
            return self._readline_matches[0]

        elif state < len(self._readline_matches):
            # Next try
            return self._readline_matches[state]

        return None
示例#46
0
def _tab_complete_init(items, post_prompt, insensitive, fuzzy, stream):
    '''Create and use a tab-completer object'''
    # using some sort of nested-scope construct is
    # required because readline doesn't pass the necessary args to
    # its callback functions
    def _get_matches(text, state):
        '''
        Get a valid match, given:
            text - the portion of text currently trying to complete
            state - the index 0..inf which is an index into the list
            of valid matches.
        Put another way, given the text, this function is supposed
        to return matches_for(text)[state], where 'matches_for' returns
        the matches for the text from the options.
        '''
        # a copy of all the valid options
        options = [o for o in items]
        # the full user-entered text
        full_text = _readline.get_line_buffer()
        # insensitivity
        if insensitive:
            options = [o.lower() for o in options]
            text = text.lower()
            full_text = full_text.lower()
        # matches
        matches = []
        try:
            # get matches
            if fuzzy:
                # space-delimited - match words
                _readline.set_completer_delims(' ')
                matches = _get_fuzzy_tc_matches(text, full_text, options)
            else:
                # not delimited - match the whole text
                _readline.set_completer_delims('')
                matches = _get_standard_tc_matches(text, full_text, options)
            # re-sensitization not necessary - this completes what's on
            # the command prompt.  If the search is insensitive, then
            # a lower-case entry will match as well as an original-case
            # entry.
        except Exception:
            # try/catch is for debugging only.  The readline
            # lib swallows exceptions and just doesn't print anything
            import traceback as _traceback
            print(_traceback.format_exc())
            raise
        return matches[state]

    def _completion_display(substitution, matches, length):
        '''
        Display the matches for the substitution, which is the
        text being completed.
        '''
        try:
            response = substitution
            stream.write("\n[!] \"{response}\" matches multiple options:\n".format(
                response=response
            ))
            if fuzzy:
                if insensitive:
                    ordered_matches = [o for o in items if substitution in o.lower()]
                else:
                    ordered_matches = [o for o in items if substitution in o]
            else:
                if insensitive:
                    ordered_matches = [o for o in items if o.lower().startswith(substitution)]
                else:
                    ordered_matches = [o for o in items if o.startswith(substitution)]
            for match in ordered_matches:
                stream.write("[!]   {}\n".format(match))
            stream.write("[!] Please specify your choice further.\n")
            # the full user-entered text
            full_text = _readline.get_line_buffer()
            stream.write(post_prompt + full_text)
            stream.flush()
        except Exception:
            # try/catch is for debugging only.  The readline
            # lib swallows exceptions and just doesn't print anything
            #import traceback as _traceback
            #print(_traceback.format_exc())
            raise

    # activate tab completion
    # got libedit bit from:
    # https://stackoverflow.com/a/7116997
    # -----------------------------------
    if "libedit" in _readline.__doc__:
        # tabcompletion init for libedit
        _readline.parse_and_bind("bind ^I rl_complete")
    else:
        # tabcompletion init for actual readline
        _readline.parse_and_bind("tab: complete")
    # -----------------------------------
    # set the function that will actually provide the valid completions
    _readline.set_completer(_get_matches)
    # set the function that will display the valid completions
    _readline.set_completion_display_matches_hook(_completion_display)
示例#47
0
import sys


def stderr(*strings):
    print(*strings, file=sys.stdout)
>>>>>>> added xrandr_setup.sh and tab_complete.py


def prep_readline( completer ):
    readline.set_completer_delims( '\n\t;' )
    readline.parse_and_bind( 'tab: complete' )
<<<<<<< 55a23e4d0277ec2f24ad8098cdefb347290511fb
    readline.set_completer( completer )
=======
    readline.set_completer( completer.complete )
    readline.set_completion_display_matches_hook(completer.display_matches)

>>>>>>> added xrandr_setup.sh and tab_complete.py

def _list_dir( directory ):
    files = []
    for filename in os.listdir( directory ):
        path = os.path.join( directory, filename )
        if os.path.isdir( path ):
            files.append( '{}{}'.format( path, os.sep ) )
        files.append( filename )
    return files

<<<<<<< 55a23e4d0277ec2f24ad8098cdefb347290511fb
=======
示例#48
0
文件: cli.py 项目: plajjan/spcli
    def tab_complete(self, text, state):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """

        # TODO: we should probably do some syntax and value validation here as well

        """
        -- Flow --
        complete or display shorthelp?

        1) Tokenize input
        2) Where are we right now in the CLI structure?
        3) Do a lookup on how the list of possible completions should be 
           sought
        4) Get the list of all completions on this level
        5) Match it up with whatever the user might already have written
        """
        from copy import copy
        import readline
        txt = readline.get_line_buffer()

        tokens = txt.split()
        if len(tokens) > 0 and txt[-1:] != ' ':
            tokens.pop()
        all_tokens = copy(tokens)

        """ TODO: fix this ? shit! """
        if (txt[-1:] == '?'):
            readline.set_completion_display_matches_hook(self.shorthelp_print)
        else:
            readline.set_completion_display_matches_hook(self.tab_print)

        if self.mode == 'operational':
            data = self.traverse(self.tree_operational, 1, tokens, all_tokens)
        else:
            data = self.traverse(self.tree_config, 1, tokens, all_tokens)


        # if last token is a leaf, then it requires a value and so we simply
        # return an empty list since we don't do value completion yet
        if len(tokens) > 0:
            lc = tokens[-1:][0]
            for obj in data:
                if obj['name'] == lc:
                    if obj['tree_type'] == 'leaf':
                        return []

        # fallback?
        if len(tokens) > 0:
            result = []
            for obj in data:
#                if obj['tree_type'] == 'value':
#                    continue
                if obj['name'] not in all_tokens:
                    result.append(obj)
            data = copy(result)


        # don't append 'value' types to tab-completion
        # ie, 'ping ttl <value>' should not have '<value>' be completed
        ac = []
        for obj in data:
            if obj['tree_type'] != 'value':
                pass
            try:
                if obj['hidden'] == True:
                    continue
            except:
                ac.append(obj['name'])

        pc = []

        """ 4) Match it up with whatever the user might already have written
        """
        for val in ac:
            if val[0:len(text)] == text:
                pc.append(val)

        try:
            return pc[state]
        except:
            return None
示例#49
0
    def __init__(self, preferences_dir=None):
        """
        Creates a new ConfigShell.
        @param preferences_dir: Directory to load/save preferences from/to
        @type preferences_dir: str
        """
        self._current_node = None
        self._root_node = None
        self._exit = False

        # Grammar of the command line
        command = locatedExpr(Word(alphanums + "_"))("command")
        var = Word(alphanums + "_\+/.<>()~@:-%]")
        value = var
        keyword = Word(alphanums + "_\-")
        kparam = locatedExpr(keyword + Suppress("=") + Optional(value, default=""))("kparams*")
        pparam = locatedExpr(var)("pparams*")
        parameter = kparam | pparam
        parameters = OneOrMore(parameter)
        bookmark = Regex("@([A-Za-z0-9:_.]|-)+")
        pathstd = Regex("([A-Za-z0-9:_.]|-)*" + "/" + "([A-Za-z0-9:_./]|-)*") | ".." | "."
        path = locatedExpr(bookmark | pathstd | "*")("path")
        parser = Optional(path) + Optional(command) + Optional(parameters)
        self._parser = parser

        if tty:
            readline.set_completer_delims("\t\n ~!#$^&()[{]}\|;'\",?")
            readline.set_completion_display_matches_hook(self._display_completions_python)

        self.log = log.Log()

        if preferences_dir is not None:
            preferences_dir = os.path.expanduser(preferences_dir)
            if not os.path.exists(preferences_dir):
                os.makedirs(preferences_dir)
            self._prefs_file = preferences_dir + "/prefs.bin"
            self.prefs = prefs.Prefs(self._prefs_file)
            self._cmd_history = preferences_dir + "/history.txt"
            self._save_history = True
            if not os.path.isfile(self._cmd_history):
                try:
                    open(self._cmd_history, "w").close()
                except:
                    self.log.warning(
                        "Cannot create history file %s, " % self._cmd_history + "command history will not be saved."
                    )
                    self._save_history = False

            if os.path.isfile(self._cmd_history) and tty:
                try:
                    readline.read_history_file(self._cmd_history)
                except IOError:
                    self.log.warning("Cannot read command history file %s." % self._cmd_history)

            if self.prefs["logfile"] is None:
                self.prefs["logfile"] = preferences_dir + "/" + "log.txt"

            self.prefs.autosave = True

        else:
            self.prefs = prefs.Prefs()
            self._save_history = False

        try:
            self.prefs.load()
        except IOError:
            self.log.warning("Could not load preferences file %s." % self._prefs_file)

        for pref, value in self.default_prefs.iteritems():
            if pref not in self.prefs:
                self.prefs[pref] = value

        self.con = console.Console()
def start_adminconsole(host,port):
	"starts the admin console"

	#########
	#gmeadmin
	#########

	class gmeadmin(_gmechild):

		def __init__(self,parent=None):
			_gmechild.__init__(self,parent,filename=__file__)
			self.smtp= None
			self.host="localhost"
			self.port=0
			self.timer=_mytimer()

		#########
		#_sendcmd
		#########

		def _sendcmd(self, cmd,arg=""):

			if self.smtp==None:
				return (None,None)

			self.smtp.putcmd(cmd,arg)
			(code, msg) = self.getreply()
			print(msg.decode("UTF-8",unicodeerror))
			return (code, msg)

		#########
		#getreply
		#########

		def getreply(self):

			if self.smtp==None:
					return None

			return self.smtp.getreply()

		######
		#start
		######

		def start(self,host="localhost",port=0):
			self.host=host
			self.port=port

			try:
				self.smtp=smtplib.SMTP(host=host,port=port)
			except:
				print("Connection not possible")
				exit(1)

			print("gpgmailencrypt admin console")
			print("============================")

			try:
				self.smtp.starttls()
			except:
				print("WARNING. Connection is not encrypted. "
					"STARTTLS was not possible")

			user=input("User: "******"Password: "******"\x00%s\x00%s"%(
										user,
										password)
						).encode("UTF-8"))[:-1]
			code,msg=self._sendcmd("ADMIN",auth.decode("UTF-8",unicodeerror))
			code,msg=self._sendcmd("AUTH PLAIN",auth.decode("UTF-8",
															unicodeerror))

			if code!=235:
				print("Authentication failed")
				exit(1)

			print("Welcome. Enter 'HELP' for a list of commands")
			self.timer.start(10,60)

			while True:
				i=""

				try:

					try:
						i=input("> ").upper()
					except (KeyboardInterrupt,EOFError):
						i="QUIT"

					self.timer.set_alive()

					if not self.timer.is_running():
						print("Automatic logout due to inactivity")
						i="QUIT"

					res=i.split(" ")
					i=res[0].upper()
					args=""

					try:
						args=" ".join(res[1:])
					except:
						pass

					cmd=""

					if i in _gpgmailencryptserver.ADMINALLCOMMANDS:

						if i=="HELP":
							self.print_help()
						else:
							self._sendcmd(i,args)

					else:
						print("Error: command '%s' unknown"%i)

				except:
					print("Error sending admin command, perhaps server is down")
					#print( sys.exc_info())
					i="QUIT"

				if i=="QUIT":
					break

			self.timer.stop()

		###########
		#print_help
		###########

		def print_help(self):
			space=18
			print("\nAllowed commands:")
			print("=================")
			print("flush".ljust(space)+"tries to re-send deferred emails")
			print("debug true/false".ljust(space)+"sets the debug mode")
			print("deluser".ljust(space)+"deletes a user")
			print("".ljust(space)+"example: 'deluser john'")
			print("help".ljust(space)+"this help")
			print("messages".ljust(space)+
					"shows all systemwarnings and -errors")
			print("quit".ljust(space)+"leave the console")
			print("quarantine".ljust(space)+
			"handles the quarantine queue")
			print("".ljust(space)+"quarantine show : shows the queue ")
			print("".ljust(space)+"                        first value is"
			" the id")
			print("".ljust(space)+"quarantine delete  xxx: deletes an entry")
			print("".ljust(space)+"                        xxx is the id'")
			print("".ljust(space)+"quarantine release xxx: sends the mail")
			print("".ljust(space)+"                        xxx is the id'")
			print("".ljust(space)+"quarantine forward xxx emailadress:")
			print("".ljust(space)+"                        forwards the email"
			" to 'emailaddress'")
			print("".ljust(space)+"                        xxx is the id")
			print("reload".ljust(space)+"reloads the configuration file")
			print("resetmessages".ljust(space)+
					"deletes all old systemmessages")
			print("resetstatistics".ljust(space)+
					"sets all statistic values to 0")
			print("setuser".ljust(space)+
			"adds a new user or changes the password for an existing user")
			print("".ljust(space)+"example: 'setuser john johnspassword'")
			print("statistics".ljust(space)+"print statistic information")
			print("users".ljust(space)+"print users")
			print("createtable".ljust(space)
			+"creates a specific SQL table")
			print("".ljust(space)+"allowed values:")
			print("".ljust(space)+"all/usermap/encryptionmap/smime/pdf")

#class taken from http://stackoverflow.com/questions/20625642/\
#				 autocomplete-with-readline-in-python3

	class MyCompleter(object):  # Custom completer

		def __init__(self, options):
			self.options = sorted(options)

		#########
		#complete
		#########

		def complete(   self,
						text,
						state):

			if state == 0:  # on first trigger, build possible matches

				if not text:
					self.matches = self.options[:]
				else:
					self.matches = [s for s in self.options
									  if (s
									  and s.upper().startswith(text.upper() ))
								   ]

			try:
				return self.matches[state]
			except IndexError:
				return None

		################
		#display_matches
		################

		def display_matches(	self,
								substitution,
								matches,
								longest_match_length):
			print()
			print(matches)
			print("> %s"%substitution,end="")
			sys.stdout.flush()
			columns = environ.get("COLUMNS", 80)
			line_buffer = readline.get_line_buffer()
			tpl = "{:<" + str(int(max(map(len, matches)) * 1.2)) + "}"
			buffer = ""

			for match in matches:
				match = tpl.format(match[len(substitution):])

				if len(buffer + match) > columns:
					print(buffer)
					buffer = ""

				buffer += match

			if buffer:
				print(buffer)

			print("> ", end="")
			print(line_buffer, end="")
			sys.stdout.flush()

	try:
		completer = MyCompleter(_gpgmailencryptserver.ADMINALLCOMMANDS)
		readline.set_completer_delims(' \t\n;')
		readline.set_completer(completer.complete)
		readline.parse_and_bind('tab: complete')
		readline.set_completion_display_matches_hook(completer.display_matches)
	except:
		print("python3 module 'readline' not installed, "
				"starting without autocompletion")
	g=gmeadmin()
	g.start(host,port)
示例#51
0
        print(f'{self.prompt} ', readline.get_line_buffer(), sep='', end='')
        sys.stdout.flush()
        return


def get_class_members(klass):
    if klass in {EAdict}:
        return {'dic'}
    ret = dir(klass)
    if hasattr(klass, '__bases__'):
        for base in klass.__bases__:
            ret = ret + get_class_members(base)
    return ret


try:
    import readline
except ImportError:
    _readline_available = False
else:
    sc = SVutilCompleter()
    readline.set_completer(sc.complete)
    # Release references early at shutdown (the readline module's
    # contents are quasi-immortal, and the completer function holds a
    # reference to globals).
    atexit.register(lambda: readline.set_completer(None))
    _readline_available = True
    readline.set_completion_display_matches_hook(sc.SV_display_hook)
    #sc.SV_display_hook(None, ['123','456','789'], 5)
    #print(EAdict([1,2,3]).__svcompleterfmt__(1,'1'))
示例#52
0
    def __init__(self, preferences_dir=None):
        '''
        Creates a new ConfigShell.
        @param preferences_dir: Directory to load/save preferences from/to
        @type preferences_dir: str
        '''
        self._current_node = None
        self._root_node = None
        self._exit = False

        # Grammar of the command line
        command = locatedExpr(Word(alphanums + '_'))('command')
        var = Word(alphanums + '_\+/.<>()~@:-%]')
        value = var
        keyword = Word(alphanums + '_\-')
        kparam = locatedExpr(keyword + Suppress('=') + Optional(value, default=''))('kparams*')
        pparam = locatedExpr(var)('pparams*')
        parameter = kparam | pparam
        parameters = OneOrMore(parameter)
        bookmark = Regex('@([A-Za-z0-9:_.]|-)+')
        pathstd = Regex('([A-Za-z0-9:_.]|-)*' + '/' + '([A-Za-z0-9:_./]|-)*') \
                | '..' | '.'
        path = locatedExpr(bookmark | pathstd | '*')('path')
        parser = Optional(path) + Optional(command) + Optional(parameters)
        self._parser = parser

        if tty:
            readline.set_completer_delims('\t\n ~!#$^&()[{]}\|;\'",?')
            readline.set_completion_display_matches_hook(
                self._display_completions_python)

        self.log = log.Log()

        if preferences_dir is not None:
            preferences_dir = os.path.expanduser(preferences_dir)
            if not os.path.exists(preferences_dir):
                os.makedirs(preferences_dir)
            self._prefs_file = preferences_dir + '/prefs.bin'
            self.prefs = prefs.Prefs(self._prefs_file)
            self._cmd_history = preferences_dir + '/history.txt'
            self._save_history = True
            if not os.path.isfile(self._cmd_history):
                try:
                    open(self._cmd_history, 'w').close()
                except:
                    self.log.warning("Cannot create history file %s, "
                                     % self._cmd_history
                                     + "command history will not be saved.")
                    self._save_history = False

            if os.path.isfile(self._cmd_history) and tty:
                try:
                    readline.read_history_file(self._cmd_history)
                except IOError:
                    self.log.warning("Cannot read command history file %s."
                                     % self._cmd_history)

            if self.prefs['logfile'] is None:
                self.prefs['logfile'] = preferences_dir + '/' + 'log.txt'

            self.prefs.autosave = True

        else:
            self.prefs = prefs.Prefs()
            self._save_history = False

        try:
            self.prefs.load()
        except IOError:
            self.log.warning("Could not load preferences file %s."
                             % self._prefs_file)

        for pref, value in self.default_prefs.iteritems():
            if pref not in self.prefs:
                self.prefs[pref] = value

        self.con = console.Console()