def file_input_main(file_path: str, output: Output, connection_id_sink: ConnectionIDSink, command_sink: CommandSink, ui_state: UIState, input_func: Callable[[str], str]) -> None: ui = TerminalUI(command_sink, ui_state, input_func) logger.info('Opening ' + file_path) try: input_file = open(file_path) parse.into_sink(input_file, output, connection_id_sink) input_file.close() except FileNotFoundError: output.error(file_path + ' not found') ui.run_until_stopped() logger.info('Done with file')
def file(input_file: IO, out: Output) -> Iterator[Tuple[str, wl.Message]]: parse = True while True: try: line = input_file.readline() except KeyboardInterrupt: break if line == '': break line = line.strip() # be sure to strip after the empty check try: conn_id, msg = message(line) if parse: yield conn_id, msg except RuntimeError as e: out.unprocessed(str(e)) except: import traceback out.show(traceback.format_exc()) parse = False
def post(self): args = self.reqparse.parse_args() f = args['file'] # UUID 生成文件名 uid = str(uuid.uuid4()) suid = ''.join(uid.split('-')) type = f.filename.split('.')[-1] # 保存 url = Save_Dir + suid + "." + type f.save(os.path.join(Save_Dir, suid + "." + type)) return Output.success(url)
def show_help(out: Output) -> None: path = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'matchers.md') text = open(path, 'r').read() text = re.sub(r'# Matchers\n\n', '', text, flags=re.MULTILINE) text = re.sub(r'\| Matcher\s*\| Description \|\n', '', text, flags=re.MULTILINE) text = re.sub(r'\| ---\s*\| --- \|\n', '', text, flags=re.MULTILINE) matches = re.findall(r'^\|\s*`(.*)`\s*\|(.*)\|$', text, flags=re.MULTILINE) parts = re.split(r'^\|.*\|$', text, flags=re.MULTILINE) assert len(matches) + 1 == len(parts) result = parts[0] for i, match in enumerate(matches): result += color(object_type_color, match[0]) result += ' ' * (32 - len(match[0])) result += color(object_id_color, match[1]) result += parts[i + 1] out.show(result)
def get(self): args = self.reqparse.parse_args() image_url = args['image_url'] image_file = glob(image_url) if len(image_file) < 1: print("") return Output.error("文件不存在!请先上传文件再进行识别!") image = np.array(Image.open(image_file).convert('RGB')) t = time.time() result, image_framed = ocr.model(image) print("Mission complete, it took {:.3f}s".format(time.time() - t)) print("\nRecognition Result:\n") data = '' for key in result: print(result[key][1]) # data.append(result[key][1]) data += result[key][1] # val.val() return Output.success(data)
def main(csv_file, out_folder): bees = CSVLoader.load_from_csv(csv_file) Output.dump_bees_to_folder(bees, out_folder)
def main(out_stream: stream.Base, err_stream: stream.Base, argv: List[str], input_func: Callable[[str], str]) -> None: ''' Parse arguments and run wayland-debug out_stream: An instance of stream.Base to use for output err_stream: An instance of stream.Base to use for logging and errors argv: A list of str arguments (should include the program name like sys.argv) input_func: the input builtin, or a mock function that behaves the same ''' # If we want to run inside GDB, the rest of main does not get called in this instance of the script # Instead GDB is run, an instance of wayland-debug is run inside it and main() is run in that # gdb_plugin.runner.parse_args() will check if this needs to happen, and gdb_plugin.run_gdb() will do it gdb_runner_args = gdb_plugin.runner.parse_args(argv) if gdb_runner_args: gdb_plugin.run_gdb(gdb_runner_args, False) return import argparse parser = argparse.ArgumentParser( description= 'Debug Wayland protocol messages, see https://github.com/wmww/wayland-debug for additional info' ) parser.add_argument('--matcher-help', action='store_true', help='show how to write matchers and exit') parser.add_argument( '-v', '--verbose', action='store_true', help='verbose output, mostly used for debugging this program') parser.add_argument('-l', '--load', dest='path', type=str, help='load WAYLAND_DEBUG=1 messages from a file') parser.add_argument( '-p', '--pipe', action='store_true', help= 'receive WAYLAND_DEBUG=1 messages from stdin (note: messages are printed to stderr so you may want to redirect using 2>&1 before piping)' ) parser.add_argument('-s', '--supress', action='store_true', help='supress non-wayland output of the program') parser.add_argument( '-c', '--color', action='store_true', help='force color output (default for interactive sessions)') parser.add_argument( '-C', '--no-color', action='store_true', help='disable color output (default for non-interactive sessions)') parser.add_argument( '-f', '--filter', dest='f', type=str, help='only show these objects/messages (see --matcher-help for syntax)' ) parser.add_argument( '-b', '--break', dest='b', type=str, help='stop on these objects/messages (see --matcher-help for syntax)') parser.add_argument( '-g', '--gdb', action='store_true', help= 'run inside gdb, all subsequent arguments are sent to gdb, when inside gdb start commands with \'wl\'' ) # NOTE: -g/--gdb is here only for the help text, it is processed without argparse in gdb_runner.main() args = parser.parse_args( args=argv[1:]) # chop off the first argument (program name) assert not args.gdb, 'GDB argument should have been intercepted by gdb_plugin.runner.parse_args()' if args.no_color: set_color_output(False) elif args.color: set_color_output(True) verbose = bool(args.verbose) unprocessed_output = not bool(args.supress) output = Output(verbose, unprocessed_output, out_stream, err_stream) if verbose: set_verbose(True) logger.info('Verbose output enabled') if args.no_color: if args.color: output.warn( 'Ignoring --color, since --no-color was also specified') logger.info('Color output disabled') elif args.color: # Print message in rainbow colors s = '' for i, c in enumerate('Color output enabled'): s += color('1;' + str(i % 6 + 31), c) logger.info(s) if unprocessed_output: logger.info('Showing unparsable output') if args.matcher_help: matcher.show_help(output) return filter_matcher = matcher.always if args.f: try: filter_matcher = matcher.parse(args.f).simplify() logger.info('Filter matcher: ' + str(filter_matcher)) except RuntimeError as e: output.error(e) stop_matcher = matcher.never if args.b: try: stop_matcher = matcher.parse(args.b).simplify() logger.info('Break matcher: ' + str(stop_matcher)) except RuntimeError as e: output.error(e) protocol.load_all(output) connection_list = ConnectionManager() ui_controller = Controller(output, connection_list, filter_matcher, stop_matcher) file_path = args.path input_from_pipe = args.pipe if check_gdb(): try: if file_path is not None or input_from_pipe: output.warn( 'Ignoring load/pipe argument because we\'re inside GDB') gdb_plugin.plugin.Plugin(output, connection_list, ui_controller, ui_controller) except: import traceback traceback.print_exc() elif file_path is not None: if input_from_pipe: output.warn('Ignoring piped input because load file is specified') file_input_main(file_path, output, connection_list, ui_controller, ui_controller, input_func) elif input_from_pipe: if args.b: output.warn( 'Ignoring stop matcher when stdin is used for messages') piped_input_main(output, connection_list) else: output.warn('No action specified') parser.print_help()
def internet_on(): while True: list = [ 'http://apptec.cl', 'https://google.com', 'https://facebook.com', 'https://reddit.com', 'https://twitter.com' ] try: urlopen(random.choice(list), timeout=3) socketio.emit('InternetConnection', {'status': True}) time.sleep(3) except: socketio.emit('InternetConnection', {'status': False}) time.sleep(2) #Init 1 def main(params): socketio.run(app, host='0.0.0.0', debug=True) if __name__ == '__main__': acc = Accelerometer(socketio) gps = Gps(socketio, params.g, serial) out = Output(socketio, serial, params.a, params.d, params.e) try: main(params) except (KeyboardInterrupt, EOFError): log.info('Exiting.')
def test_no_unprocessed_if_disabled(self): o = Output(True, False, self.out, self.err) o.unprocessed('abc') self.assertEqual(self.out.buffer, '') self.assertEqual(self.err.buffer, '')
def test_unprocessed(self): o = Output(True, True, self.out, self.err) o.unprocessed('abc') self.assertIn('abc', self.out.buffer) self.assertEqual(self.err.buffer, '')
def test_error(self): o = Output(True, True, self.out, self.err) o.error('abc') self.assertIn('Error:', self.err.buffer) self.assertIn('abc', self.err.buffer) self.assertEqual(self.out.buffer, '')
def test_warn(self): o = Output(True, True, self.out, self.err) o.warn('abc') self.assertIn('Warning:', self.err.buffer) self.assertIn('abc', self.err.buffer) self.assertEqual(self.out.buffer, '')
def test_show_multi(self): o = Output(True, True, self.out, self.err) o.show('abc', 24, True) self.assertEqual(self.out.buffer, 'abc 24 True\n') self.assertEqual(self.err.buffer, '')
def test_show(self): o = Output(True, True, self.out, self.err) o.show('abc') o.show('xyz') self.assertEqual(self.out.buffer, 'abc\nxyz\n') self.assertEqual(self.err.buffer, '')
def set_current_executed_data(self, last_executed_line): self.results[self.current_line] = Output(self.current_line, last_executed_line)
def test_shows_matcher_help(self): ss = stream.String() out = Output(False, False, ss, stream.Null()) show_help(out) self.assertIn('show and hide messages', ss.buffer)
def show(self, out: Output) -> None: out.show( color(timestamp_color, '{:7.4f}'.format(self.timestamp)) + ' ' + str(self))
def load_all(out: Output) -> None: start = time.perf_counter() shipped_protocols_path = protocols_path() if not os.path.isdir(shipped_protocols_path): out.warn( 'Could not fined protocols shipped with Wayland Debug at ' + shipped_protocols_path + ', will look for protocols on system and fall back to simpler output when not found') files = ( discover_xml('/usr/share/wayland', out) + discover_xml('/usr/share/wayland-protocols', out) + discover_xml(shipped_protocols_path, out) ) for xml_file in files: load(xml_file, out) end = time.perf_counter() logger.info('Took ' + str(int((end - start) * 1000)) + 'ms to load ' + str(len(files)) + ' protocol files') # Come on protocols, tag your fukin enums try: interfaces['wl_data_offer'].messages['set_actions'].args['dnd_actions'].enum = 'wl_data_device_manager.dnd_action' interfaces['wl_data_offer'].messages['set_actions'].args['preferred_action'].enum = 'wl_data_device_manager.dnd_action' interfaces['wl_data_offer'].messages['source_actions'].args['source_actions'].enum = 'wl_data_device_manager.dnd_action' interfaces['wl_data_offer'].messages['action'].args['dnd_action'].enum = 'wl_data_device_manager.dnd_action' interfaces['wl_data_source'].messages['set_actions'].args['dnd_actions'].enum = 'wl_data_device_manager.dnd_action' interfaces['wl_data_source'].messages['action'].args['dnd_action'].enum = 'wl_data_device_manager.dnd_action' interfaces['wl_pointer'].messages['button'].args['button'].enum = 'fake_enums.button' interfaces['zxdg_toplevel_v6'].messages['configure'].args['states'].enum = 'state' interfaces['zxdg_toplevel_v6'].messages['resize'].args['edges'].enum = 'resize_edge' interfaces['zxdg_positioner_v6'].messages['set_constraint_adjustment'].args['constraint_adjustment'].enum = 'constraint_adjustment' interfaces['xdg_toplevel'].messages['configure'].args['states'].enum = 'state' interfaces['xdg_toplevel'].messages['resize'].args['edges'].enum = 'resize_edge' interfaces['xdg_positioner'].messages['set_constraint_adjustment'].args['constraint_adjustment'].enum = 'constraint_adjustment' interfaces['zwlr_foreign_toplevel_handle_v1'].messages['state'].args['state'].enum = 'state' interfaces['org_kde_kwin_server_decoration_manager'].messages['default_mode'].args['mode'].enum = 'mode' interfaces['org_kde_kwin_server_decoration'].messages['request_mode'].args['mode'].enum = 'mode' interfaces['org_kde_kwin_server_decoration'].messages['mode'].args['mode'].enum = 'mode' interfaces['fake_enums'] = Interface( 'fake_enums', 1, OrderedDict(), OrderedDict([( # from /usr/include/linux/input-event-codes.h 'button', Enum( 'button', False, OrderedDict([ ('left', EnumEntry('left', 0x110)), ('right', EnumEntry('right', 0x111)), ('middle', EnumEntry('middle', 0x112)), ]) ) )]) ) interfaces['wl_pointer'].messages['button'].args['button'].enum = 'fake_enums.button' except KeyError as e: print(list(interfaces)) out.warn('Could not set up enum for: ' + str(e)) # Uncomment this when debugging enum tagging """