def load_markov(filename): """markovオブジェクトを作成し、filenameから読み込みをおこなう""" markov = Markov() try: markov.load(filename) except IOError as e: print(format_error(e)) return markov
def load_random(filename): """filenameをランダム辞書として読み込みリストを返す""" try: with open(filename, encoding='utf-8') as f: return [l for l in f.read().splitlines() if l] except IOError as e: print(format_error(e)) return ['こんにちは']
def load_pattern(filename): """filenameをパターン辞書として読み込み、リストを返す。""" try: with open(filename, encoding='utf-8') as f: return [ Dictionary.make_pattern(l) for l in f.read().splitlines() if l ] except IOError as e: print(format_error(e)) return []
def message_history(args): '''Prints the selected sessions' history records at index args[0]''' _ensure_sessions_selected('history') index = -1 if len(args) == 1: try: index = -int(args[0]) except ValueError: raise errors.BadArgsError( 'history', 'history[ <index>]' ) if index > history_length: raise errors.BadArgsError( 'history', 'Selected record does not exist in the history' ) results = [] for tag in selected_sessions: # Output header results.append('~~~ Scimitar - Session: {} ~~~'.format(tag)) try: ind_rec, cout, tout, lout = sessions_history[tag][index] if ind_rec: # Check the type of indicator if ind_rec[0] == mi.indicator_error: results.append(format_error(ind_rec[1])) elif ind_rec[0] == mi.indicator_exit: session_manager.remove(tag) sessions_history.remove(tag) results.append(format_error('Session {} died.', tag)) else: results.append(cout) else: results.append(''.join([cout, tout, lout])) except IndexError: results.append(format_error('Scimitar: Record does not exist')) return modes.debugging, '\n'.join(results)
def _collect_exec_results(tasks): '''Wait until threads finish and then collect the results.''' # If sessions died during execution collect them session_casualties = [] # Results results = [] # Go through the results for tag, task in tasks.iteritems(): task.join() try: mi_response = task.report() # Add it to message history stash sessions_history[tag].append(mi_response) # Output header results.append('~~~ Scimitar - Session: {} ~~~'.format(tag)) ind_rec, cout, tout, lout = mi_response # Check the type of indicator # Error if ind_rec[0] == mi.indicator_error: results.append(format_error(ind_rec[1])) # Exit elif ind_rec[0] == mi.indicator_exit: session_manager.remove(tag) sessions_history.remove(tag) results.append(format_error('Session {} died.', tag)) # Connected, Success, etc else: results.append(cout) # When the session is dead except console.SessionDiedError: # It is not a session we can work with in future session_manager.remove(tag) sessions_history.remove(tag) selected_sessions.remove(tag) # Add this session to casualty list session_casualties += [tag] return results, session_casualties
def load_template(filename): """filenameをテンプレート辞書として読み込み、ハッシュを返す""" templates = defaultdict(lambda: []) try: with open(filename, encoding='utf-8') as f: for line in f: count, template = line.strip().split('\t') if count and template: count = int(count) templates[count].append(template) return templates except IOError as e: print(format_error(e)) return templates
def lint_error(path, line, col, errname, errdesc): _lint_results['warnings'] = _lint_results['warnings'] + 1 print util.format_error(conf_['output-format'], path, line, col, errname, errdesc)
def lint_error(path, line, col, errname, errdesc): _lint_results['warnings'] = _lint_results['warnings'] + 1 print util.format_error(conf_['output-format'], path, line, col, errname, errdesc)
def gdb_exec(cmd): '''Runs the provided user command cmd on all selected sessions.''' class RemoteCommandExecutingThread(threading.Thread): '''This thread type is responsible for running commands on terminal''' def __init__(self, term, cmd): super(RemoteCommandExecutingThread, self).__init__() self.term = term self.cmd = cmd self.error = None self.result = None def run(self): '''Start the execution''' try: self._run() except Exception as e: self.error = e def _run(self): # Send the command gdb_response = self.term.query(self.cmd) # In case GDB dies if gdb_response in (r'^exit', r'^kill'): raise console.SessionDiedError else: self.result = mi.parse(gdb_response) def report(self): if self.error: raise self.error return self.result def _sanitize_gdb_command(cmd): '''Explicitly tell GDB that this is not an MI command following. Tries to differentiate between control signals and commands.''' if cmd and not repr_str_dict.has_key(cmd[0]): return ['-interpreter-exec', 'console'] + cmd return cmd def _parallel_exec_async(cmd, tag, target_sessions): '''Start running the provided cmd per each target session in separate thread ''' tasks = {} for tag in target_sessions: # Get the session cs = session_manager.get(tag) exctr = RemoteCommandExecutingThread(cs, ' '.join(cmd)) exctr.start() tasks[tag] = exctr return tasks def _collect_exec_results(tasks): '''Wait until threads finish and then collect the results.''' # If sessions died during execution collect them session_casualties = [] # Results results = [] # Go through the results for tag, task in tasks.iteritems(): task.join() try: mi_response = task.report() # Add it to message history stash sessions_history[tag].append(mi_response) # Output header results.append('~~~ Scimitar - Session: {} ~~~'.format(tag)) ind_rec, cout, tout, lout = mi_response # Check the type of indicator # Error if ind_rec[0] == mi.indicator_error: results.append(format_error(ind_rec[1])) # Exit elif ind_rec[0] == mi.indicator_exit: session_manager.remove(tag) sessions_history.remove(tag) results.append(format_error('Session {} died.', tag)) # Connected, Success, etc else: results.append(cout) # When the session is dead except console.SessionDiedError: # It is not a session we can work with in future session_manager.remove(tag) sessions_history.remove(tag) selected_sessions.remove(tag) # Add this session to casualty list session_casualties += [tag] return results, session_casualties # # gdb_exec starts here # # Ensure there are selected sessions _ensure_sessions_selected('gdb:cmd(?)') # Make sure selected sessions are valid _ensure_valid_sessions_selected('gdb:cmd(?)') # GDB launch command cmd = _sanitize_gdb_command(cmd) # Threads that run the command tasks = _parallel_exec_async(cmd, tag, selected_sessions) # Wait for all commands to finish session_casualties, results = _collect_exec_results(tasks) # In case we had dead sessions the command has essentially failed. if session_casualties: results.append( format_error( 'Session(s) {} died.', ', '.join(session_casualties) ) ) return modes.debugging, '\n'.join(results)
def lint_error(path, line, col, errname, errdesc): _lint_results["warnings"] = _lint_results["warnings"] + 1 print util.format_error(conf_["output-format"], path, line, col, errname, errdesc)