def handleChatMessage(self, myChatMessage): # Following lines sourced from stackoverflow # # http://stackoverflow.com/questions/2082387/reading-input-from-raw-input-without-having-the-prompt-overwritten-by-other-th # Next line said to be reasonably portable for various Unixes (rows,cols) = struct.unpack('hh', fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ,'1234')) text_len = len(readline.get_line_buffer())+2 # ANSI escape sequences (All VT100 except ESC[0G) # Clear current line # sys.stdout.write('\x1b[2K') # Move to start of line # sys.stdout.write('\x1b[1A\x1b[2K'*int(text_len/cols)) # Move to start of line # sys.stdout.write('\x1b[0G') # Print received message # print(myChatMessage.id.clientName + ": " + myChatMessage.textMessage) # Print the message that came before # sys.stdout.write(' >> ' + readline.get_line_buffer()) sys.stdout.flush() return 1
def recv_thread(mssg): global ClientB, ClientA, CS, Client, cipher1, cipher2, quit data_enc = "" data_unenc = "" prompt = "[" + ClientA + "]: " if (mssg == 1): while quit == False: data_enc = Client.recv(1024) data_unenc = cipher2.decrypt(data_enc) if (data_unenc == "quit()"): quit = True break sys.stdout.write('\r'+' '*(len(readline.get_line_buffer())+2)+'\r') #print "[" + ClientB + " Encrypted]: " + data_enc print "[" + ClientB + "]: " + data_unenc sys.stdout.write(prompt + readline.get_line_buffer()) sys.stdout.flush() if (mssg == 2): while quit == False: data_enc = CS.recv(1024) data_unenc = cipher1.decrypt(data_enc) if (data_unenc == "quit()"): quit = True break sys.stdout.write('\r'+' '*(len(readline.get_line_buffer())+2)+'\r') #print "[" + ClientB + " Encrypted]: " + data_enc print "[" + ClientB + "]: " + data_unenc sys.stdout.write(prompt + readline.get_line_buffer()) sys.stdout.flush()
def _complete(self, text, state): """Generic readline completion entry point.""" try: buffer = readline.get_line_buffer() line = readline.get_line_buffer().split() if " " in buffer: return [] # show all commandspath if not line: all_cmnds = [c + " " for c in self.matching_words] if len(all_cmnds) > state: return all_cmnds[state] else: return [] cmd = line[0].strip() if cmd in self.matching_words: return [cmd + " "][state] results = [c + " " for c in self.matching_words if c.startswith(cmd)] + [None] if len(results) == 2: if results[state]: return results[state].split()[0] + " " else: return [] return results[state] except Exception, e: self._tprint("[!] Completion error: %s" % e)
def complete(self, text, state): # +------/ recreating complete with iter concepts \-------{{{ # | TODO | recreating complete with iter concepts # +-------/ 9929f175-52d6-4d04-81da-44dd133b7886 \--------}}} results = [] tmp_results = [] cmd_line = [[y for y in x.split(':')] for x in shlex.split(readline.get_line_buffer())] if readline.get_line_buffer()[-1] == ' ': cmd_line.append(['']) L.debug(cmd_line) if len(cmd_line) < 1: results = [x for x in self] else: tmp_results = [] cmd = self.find(cmd_line[0]) self.params = [self.params[0]] + cmd.params for arg, data in zip(cmd_line, self.params + [ None ]): tmp_results = [] if data: tmp_results = [x for x in data.find(arg)] if tmp_results: results = tmp_results results = [ x + ':' for x in results if x.startswith(text.replace(':', ''))] return results[state]
def complete(self, text, state): buffer = readline.get_line_buffer() line = readline.get_line_buffer().split() if not line: return [c + ' 'for c in self.commands[self.mode].keys()][state] if self.re_space.match(buffer): line.append('') cmd = line[0].strip() if cmd in self.commands[self.mode].keys(): impl = getattr(self, 'complete_%s' % "extra") args = line[1:] if args: return (impl(args) + [None])[state] return [cmd + ''][state] if cmd.startswith('/'): impl = getattr(self, 'complete_%s' % "extra") args = line[0:] if args: return (impl(args) + [None])[state] return [cmd + ''][state] results = [ c + '' for c in self.commands[self.mode].keys() if c.startswith(cmd)] + [None] return results[state]
def complete(self, text, state): if readline.get_line_buffer()[0] == '!': if text: # shell command, get possiblities fullLine = readline.get_line_buffer().split(' ')[-1] self.matches = self.bash_autocomplete(fullLine) else: self.matches = [] else: level = len(readline.get_line_buffer().split(' ')) if state == 0: if text: if level == 1: self.matches = [s for s in self.firstOptions if s and s.startswith(text)] elif level == 2: self.matches = [s for s in self.secondOptions if s and s.startswith(text)] else: self.matches = [] else: if level == 1: self.matches = self.firstOptions[:] elif level == 2: self.matches = self.secondOptions[:] else: self.matches = [] try: return self.matches[state] except IndexError: return None
def p(self, status=u'未侦测到游戏数据'): """ Print current deck info. """ self.ui.clear() sys.stdout.write('\r'+' '*(len(get_line_buffer())+2)+'\r') print('-' * 20) print >>self.stream, \ u'{1}方片{0}|{2}草花{0}|{3}红桃{0}|{4}黑桃{0}|'.format( Style.RESET_ALL, colorized_suits('D'), colorized_suits('C'), colorized_suits('H'), colorized_suits('S') ) print('----+' * 4) for s in '23456789TJQKA': print >>self.stream, \ '{1}{0}|{2}{0}|{3}{0}|{4}{0}|'.format( Style.RESET_ALL, #### self.card_status('D', self.deck[('D', s)]), #### self.card_status('C', self.deck[('C', s)]), #### self.card_status('H', self.deck[('H', s)]), #### self.card_status('S', self.deck[('S', s)]) ) print('-' * 20) print >>self.stream, u'最后动作:{0}'.format(status) if status != u'未侦测到游戏数据': sys.stdout.write(self.ui.pmpt + get_line_buffer()) sys.stdout.flush()
def __printToUserNow__(self): while True: # Get an item to print # text = self.printQueueNow.get() if text == self.CONST_EXIT_QUEUE: self.printQueue.task_done() break # Following lines sourced from stackoverflow # # http://stackoverflow.com/questions/2082387/reading-input-from-raw-input-without-having-the-prompt-overwritten-by-other-th # Next line said to be reasonably portable for various Unixes (rows,cols) = struct.unpack('hh', fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ,'1234')) text_len = len(readline.get_line_buffer())+2 # ANSI escape sequences (All VT100 except ESC[0G) sys.stdout.write('\x1b[2K') # Clear current line sys.stdout.write('\x1b[1A\x1b[2K'*int(text_len/cols)) # Move cursor up and clear line sys.stdout.write('\x1b[0G') # Move to start of line print(text) sys.stdout.write(' >> ' + readline.get_line_buffer()) sys.stdout.flush() # Indicate we finished processing the enqueued print request # self.printQueueNow.task_done() return 0
def complete(self, text, state): "Generic readline completion entry point." buffer = readline.get_line_buffer() line = readline.get_line_buffer().split() # show all commands if not line: return [c + ' ' for c in self.commands][state] # account for last argument ending in a space RE_SPACE = re.compile('.*\s+$', re.M) if RE_SPACE.match(buffer): line.append('') # resolve command to the implementation functions (above) cmd = line[0].strip() if cmd in self.commands: impl = getattr(self, 'complete_%s' % cmd) args = line[1:] if args: return (impl(args) + [None])[state] return [cmd + ' '][state] results = [c + ' ' for c in self.commands if c.startswith(cmd)] + [None] return results[state]
def printMessage(self, username, message): sys.stdout.write('\r'+' '*(len(readline.get_line_buffer())+2)+'\r') color=32 if username == self.username: color=37 print '\033[1;%dm%s\033[0m: %s' % (color, username, message) sys.stdout.write(readline.get_line_buffer()) sys.stdout.flush()
def complete(self, text, state): "Generic readline completion entry point." buffer = readline.get_line_buffer() line = readline.get_line_buffer().split() if RE_SPACE.match(buffer): line.append('') args = line[0:] return (self.complete_extra(args) + [None])[state]
def output(mySocket): while True: data = mySocket.recv(1024) if not data: break sys.stdout.write('\r'+' '*(len(readline.get_line_buffer())+2)+'\r') print "<Other person>:", data sys.stdout.write('> ' + readline.get_line_buffer()) sys.stdout.flush()
def reader(socket): while True: data = socket.recv(4096) if data: sys.stdout.write('\r'+' '*(len(PROMPT)+len(readline.get_line_buffer()))+'\r') print data, sys.stdout.write(PROMPT + readline.get_line_buffer()) sys.stdout.flush()
def print_threaded(message): if not rawinput_running: print(message) return sys.stdout.write('\r'+' '*(len(readline.get_line_buffer())+2)+'\r') print(message) sys.stdout.write(CHAT_PROMPT + readline.get_line_buffer()) sys.stdout.flush()
def printCommandIndicater(): """ Print user command again """ last_line = readline.get_line_buffer() if last_line.endswith('\n'): sys.stdout.write('server command > ') else: sys.stdout.write('server command > ' + readline.get_line_buffer()) sys.stdout.flush()
def run(self): self.ui.clear() print('Initial buffer: {0}'.format(get_line_buffer())) while not self.stop.is_set(): sys.stdout.write('\r'+' '*(len(get_line_buffer())+2)+'\r') print('Interrupting text!') sys.stdout.write('> ' + get_line_buffer()) sys.stdout.flush() sleep(3)
def OnChatMembersChanged(self,chat,mambers): cnt = 0 print "\x1b[2K", #Clear current line for member in members: print "\r%2d:%s (%s)\t%s\t%s" % (cnt,user.FullName,user.Handle,user.OnlineStatus,user.MoodText) cnt += 1 self.printPrompt() print readline.get_line_buffer(), sys.stdout.flush()
def OnAsyncSearchUsersFinished(self,cookie,users): cnt = 0 print "\x1b[2K", #Clear current line for user in users: print "\r%2d:%s (%s)\t%s\t%s" % (cnt,user.FullName,user.Handle,user.OnlineStatus,user.MoodText) cnt += 1 self.printPrompt() print readline.get_line_buffer(), sys.stdout.flush()
def refreshPrompt(): global _canSend if _talkThreadRunning: if _canSend or (readline.get_line_buffer().__len__() < 1): _canSend = _canType = True sys.stdout.write(pr.IN_PROMPT+readline.get_line_buffer()) else: sys.stdout.write(pr.BAD_PROMPT) sys.stdout.flush()
def complete(self,text,state): try: tokens = readline.get_line_buffer().split() if not tokens or readline.get_line_buffer()[-1] == ' ': tokens.append(text) results = self.traverse(tokens,self.logic) + [None] return results[state] except Exception,e: print e
def output(conn, addr): while True: data = conn.recv(1024) if not data: break sys.stdout.write('\r'+' '*(len(readline.get_line_buffer())+2)+'\r') print "<Other person>:", data sys.stdout.write('> ' + readline.get_line_buffer()) sys.stdout.flush() conn.close()
def _run(self): self.ser.open() self.running = True while self.running: time.sleep(.1) if self.ser.inWaiting() > 1: self.stdout.write('\r'+' '*(len(rl.get_line_buffer())+2)+'\r') self.handle_output(self.ser.readall()) self.stdout.write(self.prompt + rl.get_line_buffer()) self.stdout.flush()
def match_display_hook(substitution, matches, longest_match_length): ## Unused args are ok. pylint: disable=W0613 """ Cleaner display for line completion """ print '\n--- possible matches ---' for match in matches: print match #print self.prompt.rstrip(), print '------------------------' print readline.get_line_buffer(), readline.redisplay()
def print(s): with _lock: if INPUT: sys.stdout.write('\r'+' '*(len(readline.get_line_buffer())+len(PROMPT))+'\r') _print(s) sys.stdout.write(PROMPT + readline.get_line_buffer()) # Needed or text doesn't show until a key is pressed sys.stdout.flush() else: _print(s)
def complete(self, text, state): buffer = readline.get_line_buffer() line = readline.get_line_buffer().split() if not line: port = ["4444"] + [None] return port[state] else: return text[state]
def print_worker(q, ps): while True: item = q.get() if item is None: break ws = ' ' * (len(readline.get_line_buffer()) + 2) sys.stdout.write('\r{}\r{}'.format(ws, item)) sys.stdout.write('{}{}'.format(ps, readline.get_line_buffer())) sys.stdout.flush() q.task_done()
def complete(self, text, state): buffer = readline.get_line_buffer() line = readline.get_line_buffer().split() cmd = line[0].strip() impl = getattr(self, 'complete_%s' % "extra") args = line[0:] if args: return (impl(args) + [None])[state] return [cmd + ''][state] return results[state]
def complete(self, text, state): buffer = readline.get_line_buffer() line = readline.get_line_buffer().split() if not line: ip = [commands.getoutput("/sbin/ifconfig").split("\n")[1].split()[1]] + [None] return ip[state] else: return text[state]
def complete(self, text, state): try: tokens = readline.get_line_buffer().split() if not tokens or readline.get_line_buffer()[-1] == ' ': results = [x + ' ' for x in list(logic[tokens[0]]) if x.startswith(text)] + [None] return results[state] tokens.append() results = self.traverse(tokens, self.logic) + [None] return results[state] except Exception: pass
def printAsynchronousOnShell(self,EventToPrint): print "" print " "+EventToPrint #this is needed because after an input, the readline buffer isn't always empty if len(readline.get_line_buffer()) == 0 or readline.get_line_buffer()[-1] == '\n': sys.stdout.write(self.envi["prompt"]) else: sys.stdout.write(self.envi["prompt"] + readline.get_line_buffer()) sys.stdout.flush()
def possible_matches(self, text): """call ``rql.suggestions`` component to complete user's input. """ # readline will only send last token, but we need the entire user's input user_input = readline.get_line_buffer() query_struct = self.match(user_input) if query_struct is None: return [] else: # we must only send completions of the last token => compute where it # starts relatively to the rql query itself. completion_offset = readline.get_begidx() - query_struct['rql_offset'] rql_query = query_struct['rql_query'] return [suggestion[completion_offset:] for suggestion in self.rsb.build_suggestions(rql_query)]
def complete(self, prefix, index): line = readline.get_line_buffer() response = None if index == 0: # This is the first time for this text, so build a match list. self.completions = self.completions_without_duplicates(line) # Return the state'th item from the match list, # if we have that many. try: response = self.completions[index] except IndexError: response = None return response
def help(cls, topic, helptxt): if cls.lasttopic == topic and \ time.time() - cls.laststamp < cls.timeout: return if helptxt: import readline cmdline = readline.get_line_buffer() print "\n%s" % helptxt if clidisplay.colors_enabled(): print "%s%s" % (term.render( clidisplay.prompt_noreadline(constants.prompt)), cmdline), else: print "%s%s" % (constants.prompt, cmdline), cls.laststamp = time.time() cls.lasttopic = topic
def prepare_words(): currtext = readline.get_line_buffer() apiname = currtext.split()[0] if apiname in self.words_db: self.is_cmd = False self.words = ['%s=' % field for field in self.api_class_params['API%sMsg' % apiname]] if apiname.startswith('Query') and not apiname in NOT_QUERY_MYSQL_APIS: real_api_name = 'API%sMsg' % apiname prepare_query_words(real_api_name) if not ('UserTag' in apiname or 'SystemTag' in apiname): self.words.append('__systemTag__=') self.words.append('__userTag__=') else: self.is_cmd = True self.words = self.words_db
def display_srvinfo(self, msg): if isinstance(msg, Text): msg = hint_to_text(msg) else: msg = colorize('[*] ', 'blue') + msg buf = readline.get_line_buffer() self.stdout.write(''.join( ['\x1b[0G', msg + '\n', '\x1b[0E\x1b[2K', self.raw_prompt, buf])) try: readline.redisplay() except Exception: pass
def __complete(text, state): """ autocompletes partial commands """ rd_buffer = readline.get_line_buffer() incomplete = True if len(rd_buffer) > 0 and rd_buffer[-1] == ' ': incomplete = False tokens = rd_buffer.split() results = [] __traverse(HIERARCHY, tokens, incomplete, results) f = lambda x: x + ' ' results = map(f, results) return results[state]
def complete(text, state): line_buffer = readline.get_line_buffer() try: line = split(line_buffer) except ValueError: return None if not line: line = [""] index = len(line) if not line_buffer.endswith(tuple(readline.get_completer_delims())): index -= 1 return [ option + " " for option in resolve(options, line[:index]) if option.startswith(text) ][state]
def start(self): while True: try: self.cmdloop() break except KeyboardInterrupt as e: if not readline.get_line_buffer(): raise KeyboardInterrupt else: print("") self.intro = None continue if self.terminal: self.terminal.kill()
def complete(self, text, state): buffer = readline.get_line_buffer() if state == 0: # on first trigger, build possible matches if not buffer: self.matches = self.accounts[:] else: self.matches = [ s for s in self.accounts if s and s.startswith(buffer) ] # return match indexed by state if state < len(self.matches): return self.matches[state][len(buffer) - len(text):] else: return None
def get_result(packet): global OUTPUT sport = packet[2].sport if (packet[1].id == 42424): result = ''.join(OUTPUT[sport]) sys.stdout.write('\r' + ' ' * (len(readline.get_line_buffer()) + 35) + '\r') print("Output from {}:".format(packet[1].src)) print(decrypt_val(result)) sys.stdout.write('[{}] Remote Shell$ '.format(args.destIP) + readline.get_line_buffer()) sys.stdout.flush() del OUTPUT[sport] elif (packet[1].id == 41414): binary_to_file(OUTPUT[sport]) del OUTPUT[sport] else: dport = packet[2].dport char1 = chr((dport >> 8) & 0xff) char2 = chr(dport & 0xff) if (char2 is not None): OUTPUT[sport] += "{}{}".format(char1, char2) else: OUTPUT[sport] += "{}".format(char1)
def complete(self, text, state): "Generic readline completion entry point." buffer = readline.get_line_buffer() line = readline.get_line_buffer().split() # show all commands if input is empty if not line: return [c + ' ' for c in COMMANDS][state] # account for last argument ending in a space if RE_SPACE.match(buffer): line.append('') # resolve command to the implementation function cmd = line[0].strip() if cmd in COMMANDS: # complete command args using `impl` impl = getattr(self, 'complete_%s' % cmd) args = line[1:] if args: return (impl(args) + [None])[state] return [cmd + ' '][state] results = [c + ' ' for c in COMMANDS if c.startswith(cmd)] + [None] return results[state]
def completenames(self, text, line, begidx, endidx): #print("Complete",text,line,begidx,endidx) query = readline.get_line_buffer().lstrip().lower() results = [] #print("Complete",text, query) for product in clProducts: if product.startswith(text): results.append(product) for persons in clPersons: if persons.startswith(text): results.append(persons) #print(results) if len(results) > 0: return results return []
def completer(self, text, state): try: self.completion_matches = [] text_u = get_line_buffer().lstrip() if text_u == "" or text_u == "help ": self.completion_matches = self.resolver.get_commands() else: if text_u[len(text_u) - 1] == " ": lines = text_u.split() while "" in lines: lines.remove("") text_u = " ".join(lines) self.completion_matches = self.resolver.get_commands( text_u) else: lines = text_u.split() while "" in lines: lines.remove("") if len(lines) == 1: commands = self.resolver.get_commands() cmds = [ cmd for cmd in commands if cmd.startswith(lines[0]) ] if len(cmds) == 1 and cmds[0] == lines[0]: self.completion_matches.append(text_u + " ") else: self.completion_matches = cmds if len(lines) > 1: args = lines[len(lines) - 1] lines.pop() line = " ".join(lines) commands = self.resolver.get_commands(line) cmds = [ cmd for cmd in commands if cmd.startswith(args) ] if len(cmds) == 1 and cmds[0] == args: self.completion_matches.append(args + " ") else: self.completion_matches = cmds if state < len(self.completion_matches): return self.completion_matches[state] else: return None except: msg = traceback.format_exc() self.error(msg) return None
def complete(self, text, state): """ Get the next possible completion for 'text'. If no complete command has been entered, then it completes against the commands provided by console and plugins. Otherwise it calls the complete_<command> method of the command. :param text: the input to complete. :param state: how many times has the method been called with the same 'text'. :return: the available completion for 'text' with state 'state'. """ if state == 0: # method has not been called for 'text', build a list of candidates. origline = readline.get_line_buffer() line = origline.lstrip() stripped = len(origline) - len(line) begidx = readline.get_begidx() - stripped if begidx > 0: # we have a prefix, hence search for a command completer. cmd, args, foo = self.parseline(line) if cmd == '': # no command has been entered, complete against available commands. compfunc = self._complete_default elif cmd in self._plugin_containers or cmd in self._system_plugin_containers: # command is provided by a Plugin, get the completer from there. if cmd in self._plugin_containers: container = self._plugin_containers[cmd] else: container = self._system_plugin_containers[cmd] try: # we need to get the completer from the container completer = container.get_completer(cmd) compfunc = completer.complete except (AttributeError, PluginError): compfunc = self._complete_default # no completer found for the command, defaulting. else: # command is provided by console. try: compfunc = getattr(self, 'complete_' + cmd) except AttributeError: compfunc = self._complete_default # no completer found, defaulting. else: # no prefix, we complete against the command names. compfunc = self._complete_commandnames self._completion_matches = compfunc( line) # get the list from the chosen completer. try: return self._completion_matches[ state] # return the completion entry for 'state'. except IndexError: return None
def interact(self): """Interact with an active session""" readline.clear_history() readline.set_completer(self.tab_complete) readline.parse_and_bind('tab: complete') command_modules = self.server.get_modules(self.type) while 1: try: #prepare command raw = input(self.get_handle()) if not raw or raw.replace(" ", "") == "": continue cmd = raw.split()[0] cmd_data = {"cmd": cmd, "args": raw[len(cmd) + 1:]} if self.needs_refresh: # don't do anything if we are in the middle of updating session pass elif cmd == "exit": self.disconnect(True) return elif cmd == "back" and self.server.is_multi: return elif cmd == "help": self.show_commands() elif cmd in list(command_modules.keys()): command_modules[cmd].run(self, cmd_data) elif cmd in list(self.server.modules_local.keys()): self.server.modules_local[cmd].run(self, cmd_data) else: try: result = self.send_command(cmd_data) if result: print(result.rstrip()) except KeyboardInterrupt: self.send_command({"cmd": "killtask"}) except KeyboardInterrupt: try: print("") if readline.get_line_buffer(): continue except: pass self.disconnect(True) return except Exception as e: print(e)
def completer(self, text, state): line = readline.get_line_buffer() items = parse_command(line) if readline.get_begidx() > len(items[0]): if items[0] not in self.commands: return None else: return self.commands[items[0]].completer( self, items, text, state) options = [i for i in self.commands.keys() if i.startswith(text)] if state < len(options): return options[state] + ' ' else: return None
def _cli_completion(text, state): line = readline.get_line_buffer()[0:readline.get_begidx()] ctx = None try: result = Interact._parser.parse(line) if not state: Interact._completion_candidates = list(result.candidates(text)) if Interact._completion_candidates: return Interact._completion_candidates.pop() return None except cly.Error: return None except Exception as e: Interact._dump_traceback(e) cly.rlext.force_redisplay() raise
def complete(self, text, state): # pylint: disable=unused-argument ''' readline tab completion callback. ''' if state == 0: self.completion_matches = [] begidx = readline.get_begidx() endidx = readline.get_endidx() line = readline.get_line_buffer() prefix = line[begidx:endidx] if line else '' line = line[:endidx] self.completion_matches = self.get_completions(line, prefix) if state < len(self.completion_matches): return self.completion_matches[state] return None
def pathCompleter(self, text, state): """ This is the tab completer for systems paths. Only tested on *nix systems """ line = readline.get_line_buffer().split() # replace ~ with the user's home dir. See https://docs.python.org/2/library/os.path.html if '~' in text: text = os.path.expanduser('~') # autocomplete directories with having a trailing slash if os.path.isdir(text): text += '/' return [x for x in glob.glob(text + '*')][state]
def complete(self, text, state): content = [] line = readline.get_line_buffer().lstrip() if self.context.connection == None: if not line or len(line) == 0: content = EngineShell.OFF_LINE_CONTENT elif not line.split(' ')[0] in EngineShell.OFF_LINE_CONTENT or \ (len(line.split(' ')) > 1 and line.split(' ')[0] == HelpCommand.name): content = [ f for f in EngineShell.OFF_LINE_CONTENT if f.startswith(text) ] if len(content) == 0: content = None return self.__do_complete(text, state, content=content)
def _generate_parameters(self, text, state): if state == 0: line = readline.get_line_buffer().lstrip() tokens = line[:readline.get_endidx()].split(' ') try: command = self._core.cmd_manager.get_command(tokens[0]) except: return None line = line[len(tokens[0]):] if not line.endswith(' '): index = line.rfind(' ') if index == -1: index = 0 line = line[:index] self._setup_completion(text, command.generate_parameters(self._core, line.strip())) return self._get_completion(text, state)
def remotePathCompleter(self, text, state): line = readline.get_line_buffer().split() if '~' in text: text = self.remote_home_dir # TODO: autocomplete directories with having a trailing slash try: fileattr = self.sftp_client.lstat(text) if stat.S_ISDIR(fileattr.st_mode): text += '/' except Exception: pass cmd = f'import glob; print([x for x in glob.glob(\'{text}\'+\'*\')])' _, stdout, _ = self.ssh_client.exec_command(f'{self.remote_conda_dir}/python -c "{cmd}"') output = stdout.readlines() return [i.strip('\'') for i in output[0].strip('\n[]').split(', ')][state]
def complete(self, text, state): """ Return the next possible completion for 'text'. """ if state == 0: line = readline.get_line_buffer().lstrip() line_parts = parse_tokens(line) if len(line_parts) <= 1: self.completion_matches = self.__complete(text, line_parts, with_params=False) else: self.completion_matches = self.__complete(text, line_parts, with_params=True) try: return self.completion_matches[state] except IndexError: return None
def complete(self, prefix, state): origline = readline.get_line_buffer() end = readline.get_endidx() origline = origline[:end] splitted_line = origline.split() if len(origline) > 0 and origline[-1] == ' ': splitted_line.append('') if state == 0: self.completeRecur(splitted_line, self.cmdTree) response = None try: response = self.curMatch[state] except IndexError: self.curMatch = [] return response + " "
def print(self, line): if self.cmdRunning: print(line) return buf = readline.get_line_buffer() tot_len = len(buf) + len(self.prompt) line_len = len(line) # erase extra characters if tot_len > line_len: for i in range(line_len - tot_len): sys.stdout.write("\b") for i in range(line_len - tot_len): sys.stdout.write(" ") sys.stdout.write("\r" + line + "\n" + self.prompt + buf)
def setConnected(self, connected): self.connected = connected old_prompt = self.prompt if self.connected: self.prompt = "pom> " else: self.prompt = "pom [disconnected]> " old_len = len(old_prompt) new_len = len(self.prompt) if new_len < old_len: for i in range(old_len - new_len): sys.stdout.write("\b") for i in range(old_len - new_len): sys.stdout.write(" ") sys.stdout.write("\r" + self.prompt + readline.get_line_buffer())
def display_matches(self, subsitution, matches, longest_match_length): line_buffer = readline.get_line_buffer() columns = environ.get("COLUMNS", 80) print() tpl = "{:<" + str(int(max(map(len, matches)) * 1.2)) + "}" buffer = "" for match in matches: match = tpl.format(match[len(subsitution):]) if len(buffer + match) > columns: print(buffer) buffer = "" buffer += match if buffer: print(buffer) print("> ", end="") sys.stdout.flush()
def getLine(): buf = readline.get_line_buffer() idx = readline.get_endidx() if 'libedit' not in readline.__doc__: return '', buf[0:idx], '' prestart = max(buf.rfind(c, 0, idx) for c in DEFAULT_DELIMS) + 1 preend = max(buf.rfind(c, 0, idx) for c in PATH_DELIMS) + 1 poststart = min( buf.find(c, idx + 1) if buf.count(c, idx + 1) else len(buf) - 1 for c in PATH_DELIMS) + 1 postend = min( buf.find(c, idx + 1) if buf.count(c, idx + 1) else len(buf) - 1 for c in DEFAULT_DELIMS) + 1 return buf[prestart: preend], \ buf[preend: poststart], \ buf[poststart: postend]
def complete_wrapper(text, state): line = readline.get_line_buffer().strip() if line == '': return None if state > 0 else self.tab if state == 0: if line.startswith('import') or line.startswith('from'): completer.matches = [name for name in modlist if name.startswith(text)] else: match = completer.complete(text, state) if match is None and '/' in text: completer.matches = glob.glob(text+'*') try: match = completer.matches[state] return '{}{}'.format(match, ' ' if keyword.iskeyword(match) else '') except IndexError: return None
def list_completer(text, state): """ from set_completer doc: The completer function is called as function(text, state), for state in 0, 1, 2, …, until it returns a non-string value. It should return the next possible completion starting with text. """ line = readline.get_line_buffer() if not line: return [item + " " for item in compl_list][state] else: return [ item + " " for item in compl_list if item.startswith(line) ][state]