def __printr(self, response, is_exception=False): config.logger.debug('---------------------') config.logger.debug('result from command execution') config.logger.debug(response) config.logger.debug(type(response)) if hasattr(response, 'message'): config.logger.debug(response.message) config.logger.debug('---------------------') if type(response) is str or type(response) is unicode or is_exception: if self.response_format == "plain": if is_exception: if hasattr(response, 'message'): response = response.message print response + "\n\n" + util.format_exception() else: try: obj = json.loads(response) response = obj.get("body", "No response body included") except ValueError: pass #not valid json print response elif self.response_format == "json": if is_exception: #todo: move to generate method if hasattr(response, 'message') and response.message != None and response.message != '': json_res = {"body":response.message,"success":False,"stack_trace":util.format_exception()} else: json_res = {"body":str(response),"success":False,"stack_trace":util.format_exception()} try: response = json.dumps(json_res) print response except: print json.dumps({"body":str(response),"success":False,"stack_trace":util.format_exception()}) else: try: obj = json.loads(response) except ValueError: raise MMException("Response is not valid JSON") print response elif type(response) is dict: if self.response_format == "plain": response = response.get("body", "No response body included") print response elif self.response_format == "json": response = json.dumps(response,indent=4) print response elif type(response) is list: if self.response_format == "plain": print response elif self.response_format == "json": response = json.dumps(response,indent=4) print response config.logger.debug('\n') config.logger.debug('---------------------') config.logger.debug('RESPONDING TO REQUEST') config.logger.debug('---------------------') config.logger.debug('\n') config.logger.debug(response)
def fit_polynomial(self): # return false on fail x = self.get_x() y = self.get_y() xmpp = self.lane.pd['xm_per_pix'] ympp = self.lane.pd['ym_per_pix'] ploty = self.lane.ploty # from our owning lane ut._assert(not ploty is None) try: self.fit_coeff = np.polyfit(y, x, 2) except Exception as ex: print("FIXME:%s lane boundry polyfit failed: %s" % (self.title, ut.format_exception(ex))) return False try: self.fit_x = self.fit_coeff[0] * ploty**2 + self.fit_coeff[ 1] * ploty + self.fit_coeff[2] except TypeError: # Avoids an error if fit is still none or incorrect print('fit_polynomal: failed to fit a line!') self.fit_x = 1 * ploty**2 + 1 * ploty return False ut._assert(not self.fit_x is None) return True
def finis(self, nonzerox, nonzeroy): try: self.concat_ixes() except Exception as ex: # Avoids an error if the above is not implemented fully ut.brk("%s.finis => %s" % (self.title, ut.format_exception(ex))) pass self.set_x(nonzerox[self.ix_list]) self.set_y(nonzeroy[self.ix_list])
def main(): try: config = get_arguments() do_repl(config) #if config.infile is None: # do_repl(config) #else: # do_compile(config) except Exception as e: print(u.format_exception(e, u.src_path, verbose=True))
def run_code(self, new_code): # write to tmpfile #with open(self.tmpfile,'w') as f: #f.write('\n'.join(self.code)) codestring = '\n'.join(new_code) u.b(codestring) # `use` statements if codestring.strip()[:4] == 'use ': assert codestring[: 4] == 'use ', "`use` statements can only be used at indentation level 0" items = codestring.strip().split(' ') assert len( items ) == 2, "`use` syntax is: `use IDENTIFIER` where the identifier is a filename WITHOUT '.py' included and that file is in the current directory. These limitations will be relaxed in the future." filename = items[1] + '.py' self.add_context(filename) return try: # Note that this can only take one Interactive line at a time (which may # actually be a multiline for loop etc). # A version that compiled with 'exec' or 'eval' mode and thus could # handle multiple Interactive lines at once was used in an # earlier version, look back thru the git repository if you need it. However # really you should be able to just divide up your input and call run_code multiple # times with the pieces. """ "Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition." """ as_ast = ast.parse(codestring, mode='single') # parse into a python ast object as_ast = ast.fix_missing_locations(as_ast) code = compile(as_ast, '<ast>', 'single') exec( code, self.globs ) #passing locals in causes it to only update locals and not globals, when really we just want globals to be updated. Confirmed by looking at the `code` module (pythons interactive interpreter emulator) that this is valid (tho they name the thing they pass in locals not globals). #print(ast.dump(as_ast)) self.code += new_code # keep track of successfully executed code except u.VerbatimExc as e: print(e) if self.context.compile: sys.exit(1) except Exception as e: # This is where exceptions for the code go. # TODO make em look nicer by telling format_exception this is the special case of a repl error thrown by exec() or eval() # (for this you may wanna have ast.parse() in a separate try-except to differentiate. It'll catch syntax errors specifically. print( u.format_exception(e, ['<string>', u.src_path], verbose=self.verbose_exceptions)) if self.context.compile: sys.exit(1)
def _log_error(item, e): ue = format_exception(e) if isinstance(e, DistributionNotFound): self.log.debug('Skipping "%s": ("%s" not found)', item, ue) elif isinstance(e, VersionConflict): self.log.error('Skipping "%s": (version conflict "%s")', item, ue) elif isinstance(e, UnknownExtra): self.log.error('Skipping "%s": (unknown extra "%s")', item, ue) elif isinstance(e, ImportError): self.log.error('Skipping "%s": (can\'t import "%s")', item, ue) else: self.log.error('Skipping "%s": (error "%s")', item, ue)
def debug(do_debug): try: yield None except Exception as e: if do_debug: print(''.join( traceback.format_exception(e.__class__, e, e.__traceback__))) print(util.format_exception(e, '')) pdb.post_mortem() sys.exit(1) else: raise e finally: pass
def lane_finder_pipe(self, in_img, cd=None, pd=None, vwr=None): # return processed image or None on error try: ut._assert(not in_img is None) ut._assert(type(in_img) is iu.Image) self.note_img_attrs(in_img) self.log_stage(in_img) undistorted = iu.undistort(in_img, cd, vwr=vwr) self.log_stage(undistorted) top_down = iu.look_down(undistorted, cd, vwr) self.log_stage(top_down) binary_warped = self.binary_warper(top_down, cache_dict=cd, parm_dict=pd) self.log_stage(binary_warped) self.find_pixels_all_bndrys(binary_warped) if not self.fit_polynomials(): return None lane_img = self.get_image(in_img) self.log_stage(lane_img) size = (lane_img.shape()[1], lane_img.shape()[0]) lane_img = iu.cv2WarpPerspective(lane_img, cd['M_lookdown_inv'], size, vwr=vwr) self.log_stage(lane_img, 'rewarped_lane_img') blended_img = iu.cv2AddWeighted(in_img, lane_img, alpha=pd['lane_blend_alpha'], beta=pd['lane_blend_beta'], gamma=pd['lane_blend_gamma'], title="merged") self.log_stage(blended_img) self.calc_vehicle_pos() blended_img.msgs = [] blended_img.msgs.append(self.display_vehicle_pos()) blended_img.msgs.append(self.display_curve_rad()) blended_img.putText() blended_img.title = 'annotated_blended_img' self.log_stage(blended_img) return blended_img except Exception as ex: print("FIXME:%s" % ut.format_exception(ex)) return None
def do_repl(config): #print(mk_green("Welcome to the ")+mk_bold(mk_yellow("Espresso"))+mk_green(" Language!")) # alt. could replace this with a 'communicate' code that tells repl to run its full self.code block # initialize the repl if config.infile is not None: if not os.path.isfile(config.infile): u.r(f'file {config.infile} not found') exit(1) the_repl = repl.Repl(config) for line in prelude: the_repl.run_code([line]) the_repl.update_banner() print("Boot time: {:.3f}".format(time.time() - _start_time)) # This is the important core loop! u.y(f'PID: {os.getpid()}') while True: #readline.write_history_file(histfile) #print("hist len: {} last item: {}".format(readline.get_current_history_length(), readline.get_history_item(readline.get_current_history_length()))) try: line = the_repl.get_input() u.reload_modules(verbose=the_repl.verbose_exceptions) #print(the_repl.line_idx) #the_repl = repl.Repl(repl=the_repl) # updates repl to a new version. This must be done outside of the Repl itself bc otherwise changes to methods won't be included. #print(the_repl.line_idx) the_repl.next(line) except u.VerbatimExc as e: print(e) if the_repl.context.compile: sys.exit(1) except Exception as e: #the program will never crash!!! It catches and prints exceptions and then continues in the while loop! print( u.format_exception(e, u.src_path, verbose=the_repl.verbose_exceptions)) if the_repl.context.compile: sys.exit(1)
def __printr(self, response, is_exception=False): config.logger.debug('---------------------') config.logger.debug('result from command execution') config.logger.debug(response) config.logger.debug(type(response)) config.logger.debug('---------------------') if type(response) is str or type(response) is unicode or is_exception: if self.response_format == "plain": if is_exception: if hasattr(response, 'message'): response = response.message print response + "\n\n" + util.format_exception() else: try: obj = json.loads(response) response = obj.get("body", "No response body included") except ValueError: pass #not valid json print response elif self.response_format == "json": if is_exception: #todo: move to generate method if hasattr(response, 'message'): json_res = { "body": response.message, "success": False, "stack_trace": util.format_exception() } else: json_res = { "body": str(response), "success": False, "stack_trace": util.format_exception() } try: response = json.dumps(json_res) print response except: print json.dumps({ "body": str(response), "success": False, "stack_trace": util.format_exception() }) else: try: obj = json.loads(response) except ValueError: raise MMException("Response is not valid JSON") print response elif type(response) is dict: if self.response_format == "plain": response = response.get("body", "No response body included") print response elif self.response_format == "json": response = json.dumps(response, indent=4) print response elif type(response) is list: if self.response_format == "plain": print response elif self.response_format == "json": response = json.dumps(response, indent=4) print response config.logger.debug('\n') config.logger.debug('---------------------') config.logger.debug('RESPONDING TO REQUEST') config.logger.debug('---------------------') config.logger.debug('\n') config.logger.debug(response)