def wrapper(self, *args, **kwds): #print('WC!', *args) kwc = len(args) ckwds = {} if retic_pinstance(src_fmls, rtypes.NamedParameters): for k in kwds: if k in [k for k, _ in src_fmls.parameters]: kwc -= 1 ckwds[k] = retic_cast(kwds[k], rtypes.Dyn, dict(src_fmls.parameters)[k], msg, line=line) else: ckwds[k] = kwds[k] if fml_len != -1: retic_assert(len(args)+len(kwds) == fml_len, val, msg) cargs = [ retic_mergecast(arg, trg, src, msg, line=line)\ for arg, trg, src in zip(args, trg_fmls.types(len(args)+len(kwds))[:kwc], src_fmls.types(len(args)+len(kwds))[:kwc]) ] if bi: if (base_val is eval or base_val is exec): if len(cargs) < 2 and 'globals' not in ckwds: cargs.append(inspect.getouterframes(inspect.currentframe())[2][0].f_locals) if len(cargs) < 3 and 'locals' not in ckwds: cargs.append(inspect.getouterframes(inspect.currentframe())[2][0].f_globals) ret = val(*cargs, **ckwds) elif base_val is globals: ret = inspect.getouterframes(inspect.currentframe())[2][0].f_globals elif base_val is locals: ret = inspect.getouterframes(inspect.currentframe())[2][0].f_locals else: stripped_cargs = [retic_get_actual(val) for val in cargs] stripped_ckwds = {k: retic_get_actual(ckwds[k]) for k in ckwds} ret = val(*stripped_cargs, **stripped_ckwds) else: ret = val(*cargs, **ckwds) return retic_mergecast(ret, src_ret, trg_ret, msg, line=line)
def tryCut(self): if not self.target_reached: return # Check that this whichBranch call was made from the top level function in the program # under test. # TODO: add recording of state from multiple function frames to remove this limitation caller_of_instrumented = inspect.getouterframes(inspect.currentframe())[4][3] # function name if not caller_of_instrumented == "execute": log.debug("Skip subsumption checking due to not being in top level function") return (frame, filename, line_number, function_name, lines, line_index) = inspect.getouterframes( inspect.currentframe())[3] pc = filename + ":" + str(line_number) state = dict(frame.f_locals) state.pop("__se_cond__", None) # remove __se_cond__ because it is never reused # check for subsumption for (old_state, old_constraint) in self.engine.states[pc]: if self.isSubsumed(state, old_state, old_constraint): log.debug("State subsumed: %s contained in %s" % (self.current_constraint, old_constraint)) stats.incCounter("paths cut") raise EndExecutionThrowable() # was not subsumed by anything, record state self.engine.states[pc].append((state, self.current_constraint))
def get_parents(self, current): debug_string = 'Function: ' + str(inspect.getouterframes(current)[1][3]) + ' Parents:' family = list(inspect.getouterframes(current)) for parent in family: debug_string += ' ' + str(parent[4]) print debug_string return
def __call__( self, *args, **kwargs ): """ method called each time when a decorate function is called get information about the function and create a stack of functions called """ # get key and value of args for create object to add in dataBase foncArgs = inspect.getargspec( self.fonc )[0] dico = dict() cpt = 0 while cpt < len( args ) : if foncArgs[cpt] is not 'self' : dico[foncArgs[cpt]] = args[cpt] cpt += 1 # print dico ( frame, filename, line_number, function_name, lines, index ) = inspect.getouterframes( inspect.currentframe() )[1] stack = Stack_Operation() stack.appendOperation( str( filename ) + ' ' + str( self.fonc.__name__ ) + ' ' + str( line_number ) + ' ' + str( lines ) ) if not self.parent : ( frame, filename, line_number, function_name, lines, index ) = inspect.getouterframes( inspect.currentframe() )[2] self.parent = str( filename ) + ' ' + str( function_name ) + ' ' + str( line_number ) + ' ' + str( lines ) print 'order : ', stack.order, ' depth : ', stack.depth , ' operation name : ', stack.stack[stack.depth - 1] # print 'parent ', self.parent result = self.fonc( *args, **kwargs ) stack.popOperation() return result
def make_line_header(cls): now_time = datetime.datetime.now().time() line_number = inspect.getlineno(inspect.getouterframes(inspect.currentframe())[2][0]) file_path_name = inspect.getfile(inspect.getouterframes(inspect.currentframe())[2][0]) file_name = file_path_name.split('/')[-1] line_header = '[%s] %s:%d : ' % (now_time, file_name, line_number) return line_header
def __DEBUG__(msg, level=1): if level > OPTIONS.Debug.value: return line = inspect.getouterframes(inspect.currentframe())[1][2] fname = os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1]) OPTIONS.stderr.value.write("debug: %s:%i %s\n" % (fname, line, msg))
def debug_log(var_dict, notes=''): """ Write debug log (msg) into debug.log Args: log_path: the log file path msg: the log msg Returns: Raises: Native exceptions. """ if '-debug' not in sys.argv: return #(frame, filename, line_number, function_name, lines, index) = ( # inspect.getouterframes(inspect.currentframe())[1]) filename = inspect.getouterframes(inspect.currentframe())[1][1] line_number = inspect.getouterframes(inspect.currentframe())[1][2] function_name = inspect.getouterframes(inspect.currentframe())[1][3] header = ('<%s>(%d)[%s()]' % (os.path.basename(filename), line_number, function_name)) vals = '' #keys = sorted(var_dict.keys()) #for key in keys: # vals = (('%s, %s=%s' % (vals, str(key), str(var_dict[key]))) if vals # else ('%s=%s' % (str(key), str(var_dict[key])))) for key, val in var_dict.iteritems(): vals = (('%s, %s=%s' % (vals, str(key), str(val))) if vals else ('%s=%s' % (str(key), str(val)))) msg = '%s -> %s, %s' % (header, vals, notes) with open(DEBUG_FILE, 'a') as outfile: outfile.write('%s\n' % msg)
def caller(): """Return the context of the current function call. Return a tuple (func_name, module_name, file_name, line).""" func_name= inspect.getouterframes(inspect.currentframe())[2][3] module_name = inspect.getmodule(inspect.stack()[2][0]).__name__ file_name = inspect.getmodule(inspect.stack()[2][0]).__file__ line = inspect.getouterframes(inspect.currentframe())[2][2] return (func_name, module_name, file_name, line)
def trace_calls_and_returns(frame, event, arg): co = frame.f_code filename = co.co_filename func_name = co.co_name code = inspect.getframeinfo(frame)[3] global current_trace '''if sys==None: return if func_name == 'write': # Ignore write() calls from print statements return ''' if filename=='/usr/lib/python2.7/socket.py': # use socket.__file__ to get this #print filename + '/' + func_name #traceback.print_stack(frame) previous_frames = inspect.getouterframes(frame) for parent in previous_frames: frame_details = inspect.getframeinfo(parent[0]) if frame_details[2] in functions_being_traced: #print frame_details #TODO if already in the list, don't add a duplicate current_trace.setdefault(frame_details[2],{}).setdefault('per_line_dependencies',{}).setdefault(frame_details[1],[]).append('network') if code is not None: if string.find(' '.join(code),' open(')!=-1: previous_frames = inspect.getouterframes(frame) for parent in previous_frames: frame_details = inspect.getframeinfo(parent[0]) if frame_details[2] in functions_being_traced: #print frame_details current_trace.setdefault(frame_details[2],{}).setdefault('per_line_dependencies',{}).setdefault(frame_details[1],[]).append('filesystem') #TODO want to trace child functions as well... but for that, need to know which files to ignore/not ignore #figure out based on analysis of previous_frames #return #'kw' #line_no = frame.f_lineno # ignore everything outside of these files, as built-in or third-party if func_name in functions_being_traced:#filename in files_to_trace and '''print "%s: %s %s[%s]" % ( event, frame.f_code.co_name, frame.f_code.co_filename, frame.f_lineno, )''' if event=='call': #get the input parameters #print str(frame.f_locals) current_trace.setdefault(func_name,{})['function_name'] = func_name current_trace.setdefault(func_name,{})['arg'] = copy.copy(frame.f_locals) #current_trace.setdefault(str(f.__name__),{})['kw'] = kw return trace_calls_and_returns elif event=='line': # also gets called for return events, too! return trace_lines else: return
def __call__(self, x, y, inverse=False, coords=None): from models import aacgm from copy import deepcopy import numpy as np import inspect if coords is not None and coords not in self._coordsDict: print 'Invalid coordinate system given in coords ({}): setting "{}"'.format(coords, self.coords) coords = None if coords and coords != self.coords: trans = coords+'-'+self.coords if trans in ['geo-mag','mag-geo']: flag = 0 if trans == 'geo-mag' else 1 try: nx, ny = len(x), len(y) xt = np.array(x) yt = np.array(y) shape = xt.shape y, x, _ = aacgm.aacgmConvArr(list(yt.flatten()), list(xt.flatten()), [0.]*nx, flag) x = np.array(x).reshape(shape) y = np.array(y).reshape(shape) except TypeError as e: y, x, _ = aacgm.aacgmConv(y, x, 0., flag) if self.coords is 'geo': return basemap.Basemap.__call__(self, x, y, inverse=inverse) elif self.coords is 'mag': try: callerFile, _, callerName = inspect.getouterframes(inspect.currentframe())[1][1:4] except: return basemap.Basemap.__call__(self, x, y, inverse=inverse) if isinstance(y, float) and abs(y) == 90.: return basemap.Basemap.__call__(self, x, y, inverse=inverse) if 'mpl_toolkits' in callerFile and callerName is '_readboundarydata': if not inverse: try: nx, ny = len(x), len(y) x = np.array(x) y = np.array(y) shape = x.shape yout, xout, _ = aacgm.aacgmConvArr(list(y.flatten()), list(x.flatten()), [0.]*nx, 0) xout = np.array(xout).reshape(shape) yout = np.array(yout).reshape(shape) except TypeError: yout, xout, _ = aacgm.aacgmConv(y, x, 0., 0) return basemap.Basemap.__call__(self, xout, yout, inverse=inverse) else: return basemap.Basemap.__call__(self, x, y, inverse=inverse) else: return basemap.Basemap.__call__(self, x, y, inverse=inverse) elif self.coords is 'mlt': print 'Not implemented' callerFile, _, callerName = inspect.getouterframes(inspect.currentframe())[1][1:4]
def hello(): pp(inspect.getouterframes( inspect.currentframe())) frame,filename,line_number,function_name,lines,index=\ inspect.getouterframes(inspect.currentframe())[1] print(frame,filename,line_number,function_name,lines,index) file_info = inspect.getouterframes(inspect.currentframe())[1] print(file_info[1]+":"+str(file_info[2]))
def write(level, message): (frame, filename, line_number, function_name, lines, index) = inspect.getouterframes(inspect.currentframe())[2] if filename == __file__: (frame, filename, line_number, function_name, lines, index) = inspect.getouterframes(inspect.currentframe())[3] extra={'s_filename' : filename.replace(rootpath, ''), 's_line_number' : line_number, 's_function_name' : function_name} if start.started: while not write.queue.empty(): job = write.queue.get() logging.getLogger('alarmserver').log(job['level'], job['message'], extra = job['extra']) logging.getLogger('alarmserver').log(level, message, extra = extra) else: write.queue.put({'level' : level, 'message' : message, 'extra' : extra})
def log(text, timestamp = None): def path_leaf(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) frame,filename,line_number,function_name,lines,index = inspect.getouterframes(inspect.currentframe())[2] # log caller stack filename = path_leaf(filename) _,_,_,log_type,_,_ = inspect.getouterframes(inspect.currentframe())[1] # log function (info, error...) log_type = log_type[0].upper() * 2 # II for info, EE for error... if timestamp is None: timestamp = Timestamp() text = "%s %s %s:%s: %s" %(timestamp.to_human_str(), log_type, filename, line_number, text) print text logfile.write("\n%s" %text)
def skip_lines(self, inputfile, sequence): """Read trivial line types and check they are what they are supposed to be. This function will read len(sequence) lines and do certain checks on them, when the elements of sequence have the appropriate values. Currently the following elements trigger checks: 'blank' or 'b' - the line should be blank 'dashes' or 'd' - the line should contain only dashes (or spaces) 'equals' or 'e' - the line should contain only equal signs (or spaces) 'stars' or 's' - the line should contain only stars (or spaces) """ expected_characters = { '-': ['dashes', 'd'], '=': ['equals', 'e'], '*': ['stars', 's'], } lines = [] for expected in sequence: # Read the line we want to skip. line = next(inputfile) # Blank lines are perhaps the most common thing we want to check for. if expected in ["blank", "b"]: try: assert line.strip() == "" except AssertionError: frame, fname, lno, funcname, funcline, index = inspect.getouterframes(inspect.currentframe())[1] parser = fname.split('/')[-1] msg = "In %s, line %i, line not blank as expected: %s" % (parser, lno, line.strip()) self.logger.warning(msg) # All cases of heterogeneous lines can be dealt with by the same code. for character, keys in expected_characters.items(): if expected in keys: try: assert all([c == character for c in line.strip() if c != ' ']) except AssertionError: frame, fname, lno, funcname, funcline, index = inspect.getouterframes(inspect.currentframe())[1] parser = fname.split('/')[-1] msg = "In %s, line %i, line not all %s as expected: %s" % (parser, lno, keys[0], line.strip()) self.logger.warning(msg) continue # Save the skipped line, and we will return the whole list. lines.append(line) return lines
def _add_metadata(self, loglevel, args, kwargs): """ Automatically add time, file and line number to log data """ temp_bind_dict = deepcopy(self._bind_dict) # Format UTC timestamp in ISO 8601 format temp_bind_dict['timestamp'] = ( datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")) temp_bind_dict['loglevel'] = loglevel # Use inspect to obtain caller information (file and lineno) _, file_name, line_num, _, _, _ = inspect.getouterframes( inspect.currentframe())[2] temp_bind_dict['file'] = file_name temp_bind_dict['lineno'] = line_num if len(args) > 0: # should only be 1 arg value, others are ignored temp_bind_dict['event'] = args[0] for key, val in kwargs.items(): if key.startswith(self._priv_str): self._priv_list.append(val) else: temp_bind_dict[key] = val if len(self._priv_list) > 0: temp_bind_dict[self._priv_str] = self._priv_list # Turn into JSON json_bind_dict = json.dumps(temp_bind_dict, encoding='utf-8', ensure_ascii=False) return json_bind_dict
def _inline(code, level=1, stringify=None, rpcweakrefs=None, **kwargs): # inline interpolation... prev_frame = inspect.getouterframes(inspect.currentframe())[level][0] loc = prev_frame.f_locals glo = prev_frame.f_globals for item in _rec1_inline.findall(code): rep = _evl(item, glo, loc) if not stringify: rep = rep.varname if hasattr(rep, 'varname') else str(rep) else: rep = stringify(rep, encapsulate_strings=kwargs.get('encapsulate_strings', True)) code = code.replace('#{%s}' % item, rep) if rpcweakrefs is not None: for item in _rec2_rpc.findall(code): sitem = item.split(',') litem = sitem[0].strip().replace('this.', 'self.') ritem = ','.join(sitem[1:]) fnc = _evl(litem, glo, loc) rep = str(random.randint(0, 1e16)) def ondelete(r): del rpcweakrefs[r.__rep] wr = safeRef(fnc, ondelete) wr.__rep = rep # TODO: should we check for existance first? i.e. every RPC should have its own random number, or can we reuse it? rpcweakrefs[rep] = wr code = code.replace('#rpc{%s}' % item, 'rpc(%s)' % ("'"+rep+"',"+ritem)) return code
def SaveTillDone(filename, resolution=1000, timeout=1800): """ Saves the video to a filename. The function will timeout after `resolution` x `timeout` milliseconds. :param filename: Path of video file to save to :param resolution: Frequency to poll for progress updates in milliseconds. Default: 1000 milliseconds. :param timeout: How many polls until the function is considered timed out. Default: 1800 polls. """ from .mvrt import Core caller = inspect.getouterframes(inspect.currentframe())[1][1] runname = os.path.splitext(os.path.basename(caller))[0] path = filename.replace("[CurrentStyle]", Core.GetActiveMVStyle()) \ .replace("[ConfigName]", runname) path = normalize(path) assert is_true_or_non_zero( Core.StartRenderTL2FileProc(path, None, 0, 0, 0, 0, None)), \ ("StartRenderTL2FileProc failed: " + GetLastErrorDescription()) def poll(): prog = Core.GetRenderTL2FileProgress() assert prog >= 0, "GetRenderTL2FileProgress failed: " + GetLastErrorDescription() return prog StartCheckProgress(self.poll, timeout=timeout, \ onStop=lambda: Core.StopRenderTL2FileProc())
def logFunctionAndArgs(self): frame = inspect.getouterframes(inspect.currentframe())[1][0] args, _, _, values = inspect.getargvalues(frame) frameinfo = inspect.getframeinfo(frame) functionName=inspect.getframeinfo(frame)[2] output = "" for arg in args[1:]: #[1:] skip the first argument 'self' value = values[arg] if isinstance(value, str): #add apostrophes for string values value = "\'"+value+"\'" elif isinstance(value, int): value = ''.join('%02X' % value) else: newValue = "" for i in value: if isinstance(i, int): newValue += '%02X' % i else: newValue += str(i) value = newValue output += arg + '=' + value if arg != args[-1]: #add comma if not the last element output +=',' #do not print "\n' as a new line output = output.replace("\n","\\n") self.logging.info("--> "+functionName+'('+output+')')
def factor_init(self, *args, **kwargs): frames = inspect.getouterframes(inspect.currentframe()) layer_builder_name = frames[2][3] assert (layer_builder_name.startswith('build_') and layer_builder_name.endswith('_layer')) self._layer_name = layer_builder_name[6:].replace('_', ' ').title() return orig_factor_init(self, *args, **kwargs)
def get_data_path(fn, subfolder='data'): """Return path to filename ``fn`` in the data folder. During testing it is often necessary to load data files. This function returns the full path to files in the ``data`` subfolder by default. Parameters ---------- fn : str File name. subfolder : str, defaults to ``data`` Name of the subfolder that contains the data. Returns ------- str Inferred absolute path to the test data for the module where ``get_data_path(fn)`` is called. Notes ----- The requested path may not point to an existing file, as its existence is not checked. """ # getouterframes returns a list of tuples: the second tuple # contains info about the caller, and the second element is its # filename callers_filename = inspect.getouterframes(inspect.currentframe())[1][1] path = os.path.dirname(os.path.abspath(callers_filename)) data_path = os.path.join(path, subfolder, fn) return data_path
def error(self, msg, obj=''): """"" Add error message to list """"" if not isinstance(msg, Exception): exc = Exception(msg) else: exc = msg self.exceptions.append(exc) curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) vmsg = '%s\nMethod: %s; locals: %s' % (exc, calframe[2][3], calframe[2][0].f_locals) if not obj: item = self.makeMessage(vmsg, self.config.options.error_bg_color, 'error', timestamp=True, fgcolor=self.config.options.error_fg_color) item2 = self.makeMessage(msg, self.config.options.error_bg_color, 'error', timestamp=True, fgcolor=self.config.options.error_fg_color) # in qt you cant copy widget=(( else: item = self.makeMessage('%s::%s' % (obj, vmsg), self.config.options.erorr_bg_color, 'error', timestamp=True, fgcolor=self.config.options.error_fg_color) item2 = self.makeMessage('%s::%s' % (obj, msg), self.config.options.error_bg_color, 'error', timestamp=True, fgcolor=self.config.options.error_fg_color) item.e = exc self.errorList.addItem(item) self.debugList.addItem(item2) self.app.notify(self.app.config.info.title, 'You have got ERROR!\n%s' % exc) self.app.api.setFlag(self.app.api.icons['red'])
def script_name(): # return name of script that is invoking bilder lib minus the ".py" frames = inspect.getouterframes(inspect.currentframe()) scriptframe = frames[-1] scriptname = scriptframe[1] scriptname = os.path.basename(scriptname) scriptname = scriptname[:-3] return scriptname
def execute(self, driver_command, params=None): curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe) if driver_command in [ Command.SCREENSHOT, Command.GET_PAGE_SOURCE, Command.GET_CURRENT_URL ]: return super(ScreenshotOnExceptionWebDriver, self).execute(driver_command, params=params) elif len(calframe) > 4 and calframe[4][3] in ['until', 'until_not']: return super(ScreenshotOnExceptionWebDriver, self).execute(driver_command, params=params) else: try: return super(ScreenshotOnExceptionWebDriver, self).execute(driver_command, params=params) except WebDriverException: global SAVED_FILES_PATH if SAVED_FILES_PATH: timestamp = repr(time.time()).replace('.', '') # save a screenshot screenshot_filename = SAVED_FILES_PATH + "/" + timestamp + ".png" self.get_screenshot_as_file(screenshot_filename) logger.error("Screenshot saved to %s" % screenshot_filename) # save the html html_filename = SAVED_FILES_PATH + "/" + timestamp + ".html" html = self.page_source outfile = open(html_filename, 'w') outfile.write(html.encode('utf8', 'ignore')) outfile.close() logger.error("HTML saved to %s" % html_filename) logger.error("Page URL: %s" % self.current_url) raise
def trigger_loop(self, delay=0, actor_ids=None): import inspect import traceback super(DebugScheduler, self).trigger_loop(delay, actor_ids) (frame, filename, line_no, fname, lines, index) = inspect.getouterframes(inspect.currentframe())[1] _log.debug("triggered %s by %s in file %s at %s" % (time.time(), fname, filename, line_no)) _log.debug("Trigger happend here:\n" + ''.join(traceback.format_stack()[-6:-1]))
def export_getValues( self ): ( frame, filename, line_number, function_name, lines, index ) = inspect.getouterframes( inspect.currentframe() )[0] print( frame, filename, line_number, function_name, lines, index ) #=============================================================================== # basePath = '/Resources/NewResources/' # # for nb in gConfig.getValue(basePath + 'toUse' ): # good = gConfig.getValue( basePath + 'sub' + nb + '/good', False ) # # successful = [ gConfig.getValue( basePath + 'sub' + nb + '/val' ) for nb in toUse if ] #=============================================================================== toUse = gConfig.getValue( '/Resources/NewResources/toUse', [] ) successful = [] failed = [] for num in toUse : path = '/Resources/NewResources/sub' + num + '/' good = gConfig.getValue( path + 'good', False ) if good : successful.append( gConfig.getValue( path + 'val', 'unknown' ) ) else : failed.append( gConfig.getValue( path + 'val', 'unknown' ) ) return S_OK( { 'Successful': successful, 'Failed' : failed } )
def caller(): """ Get the name of the calling function as a `str` :Returns: out : str The name of the function that called the function whose context `caller()` is called from. (Hopefully the examples makes this clearer.) :Examples: >>> def foo(): ... print caller() ... >>> def bar(): ... foo() ... >>> bar() bar >>> def foobar(): ... bar() ... >>> foobar() bar """ frame = inspect.currentframe() try: return inspect.getouterframes(frame)[2][3] finally: del frame
def is_sim_child(): # variables frame = inspect.currentframe() parent_frames = inspect.getouterframes(frame) sim_file_filename = 'mission_replay.py' base_pathname = os.path.dirname(__file__) sim_rel_pathname = '../tools/mission replay' sim_file_fileloc = os.path.join(base_pathname, sim_rel_pathname,sim_file_filename) sim_file_fileloc = os.path.abspath(sim_file_fileloc) # run breif check just to make sure mission_replay.py exists, # otherwise tell user that the file has probably been mis-named. print sim_file_fileloc if not os.path.isfile(sim_file_fileloc): print("---\nERROR: sim-file {} not found! Please check to make ".format(sim_file_filename) + "sure it is in the correct location (full check path = " + "{})".format(sim_file_fileloc)) for parent_frame in parent_frames: frame_obj = parent_frame[0] frame_name = parent_frame[1] if sim_file_filename == frame_name: return (True, frame_obj) else: pass # parent sim file not found. return (False, None)
def returnCallerFunctionName(): ''' Return the function name two frames back in the stack. This enables exceptions called to report the function from which they were called. ''' result = '[unknown function]' try: frame, filename, line_no, s_funcName, lines, index = \ inspect.getouterframes(inspect.currentframe())[2] s_moduleName = inspect.getmodule(frame) s_moduleName = "" if s_moduleName is None else s_moduleName.__name__ result = "{0}.{1}".format(s_moduleName, s_funcName) if s_funcName == '<module>': s_funcName = "<Script Editor>" if filename == "<maya console>": result = "<Maya>.{0}".format(s_funcName) except StandardError: log.exception("Failed to inspect function name") return result
def logModuleCaller(): # This works with CPython (Maya) and you can't use the generic 'getCaller' # because in this case, OR YOU CAN??? CHECK IT BETTER # Get the list of outer frames <6-uples> outerFrames = inspect.getouterframes(inspect.currentframe()) # Frame 6-uple: # 0 --> <frame object at 0x000000012D1DEB88> # 1 --> <str> module caller path # 2 --> <int> # 3 --> <module> module caller obj # 4 --> <list> caller Name, # 5 --> <int> # Actual outer frames in the stack (in this special case, we need item 2) # (0) logModuleCaller (Here) # (1) Log.__init__ (Here) # ==> (2) the caller module (The caller module, where Log(...) was called) # (3) ... ... # ... callerStackIndex = 2 moduleName = inspect.getmodulename(outerFrames[callerStackIndex][1]) del outerFrames return moduleName
def write_op2(self, op2_file, op2_ascii, itable, new_result, date, is_mag_phase=False, endian='>'): """writes an OP2""" import inspect from struct import Struct, pack frame = inspect.currentframe() call_frame = inspect.getouterframes(frame, 2) op2_ascii.write( f'{self.__class__.__name__}.write_op2: {call_frame[1][3]}\n') if itable == -1: self._write_table_header(op2_file, op2_ascii, date) itable = -3 #eids = self.element # table 4 info #ntimes = self.data.shape[0] #nnodes = self.data.shape[1] nelements = self.data.shape[1] # 21 = 1 node, 3 principal, 6 components, 9 vectors, 2 p/ovm #ntotal = ((nnodes * 21) + 1) + (nelements * 4) ntotali = self.num_wide ntotal = ntotali * nelements #print('shape = %s' % str(self.data.shape)) #assert self.ntimes == 1, self.ntimes #device_code = self.device_code op2_ascii.write(f' ntimes = {self.ntimes}\n') eids_device = self.element * 10 + self.device_code #print('ntotal=%s' % (ntotal)) #assert ntotal == 193, ntotal if not self.is_sort1: raise NotImplementedError('SORT2') struct1 = Struct(endian + b'if') fdtype = self.data.dtype if self.size == 4: pass else: print(f'downcasting {self.class_name}...') #idtype = np.int32(1) fdtype = np.float32(1.0) # [eid, stress] data_out = np.empty((nelements, 2), dtype=fdtype) data_out[:, 0] = eids_device.view(fdtype) op2_ascii.write('%s-nelements=%i\n' % (self.element_name, nelements)) for itime in range(self.ntimes): self._write_table_3(op2_file, op2_ascii, new_result, itable, itime) # record 4 itable -= 1 header = [4, itable, 4, 4, 1, 4, 4, 0, 4, 4, ntotal, 4, 4 * ntotal] op2_file.write(pack('%ii' % len(header), *header)) op2_ascii.write('r4 [4, 0, 4]\n') op2_ascii.write(f'r4 [4, {itable:d}, 4]\n') op2_ascii.write(f'r4 [4, {4 * ntotal:d}, 4]\n') # [eid, stress] data_out[:, 1] = self.data[itime, :, 0] op2_file.write(data_out) itable -= 1 header = [ 4 * ntotal, ] op2_file.write(pack('i', *header)) op2_ascii.write('footer = %s\n' % header) new_result = False return itable
def shared( function_=None, scope=_get_default_scope, scope_context=None, scope_kwargs=None, timeout=SHARE_DEFAULT_TIMEOUT, retries=DEFAULT_CALL_RETRIES, function_kw=None, inject=False, injected_kw='_injected', ): r"""Generic function sharing, share the results of any decorated function. Any parallel pytest xdist worker will wait for this function to finish :type function_: callable :type scope: str or callable :type scope_kwargs: dict :type scope_context: str :type timeout: int :type retries: int :type function_kw: list :type inject: bool :type injected_kw: str :param function_: the function that is intended to be shared :param scope: this parameter will define the namespace of data sharing :param scope_context: an added context string if applicable, of a concrete sharing in combination with scope and function. :param scope_kwargs: kwargs to be passed to scope if is a callable :param timeout: the time in seconds to wait for waiting the shared function :param retries: if the shared function call fail, how much time should retry before setting the call with in failure state :param function_kw: The function kwargs to use as an additional scope, an md5 hexdigest of that kwargs will be created and added to the storage scope, that way we should have diffrent stored values for diffrent kw values. :param inject: whether to recall the function with injecting the result as \**kwargs :param injected_kw: the kw arg to set to True to inform the function that the kwargs was injected from a saved storage """ _check_config() class_names = [] class_name = None index = 1 while class_name != '<module>' and index <= _DEFAULT_CLASS_NAME_DEPTH: if class_name: class_names.append(class_name) class_name = inspect.getouterframes(inspect.currentframe())[index][3] index += 1 class_names.reverse() class_name = '.'.join(class_names) if function_kw is None: function_kw = [] def main_wrapper(func): @functools.wraps(func) def function_wrapper(*args, **kwargs): function_kw_scope = {key: kwargs.get(key) for key in function_kw} function_name = _get_function_name(func, class_name=class_name, kwargs=function_kw_scope) if not ENABLED: # if disabled call the function immediately return func(*args, **kwargs) function_name_key = _get_function_name_key( function_name, scope=scope, scope_kwargs=scope_kwargs, scope_context=scope_context) shared_object = _SharedFunction( function_name_key, func, args=args, kwargs=kwargs, timeout=timeout, retries=retries, inject=inject, injected_kw=injected_kw, ) return shared_object() return function_wrapper def wait_function(func): return main_wrapper(func) if function_: return main_wrapper(function_) else: return wait_function
def true_debug(self, current, objects, locale): debug_string = 'Function: ' + str(inspect.getouterframes(current)[1][3]) #if locale == 'all': print inspect.getouterframes(current)[4]; return if objects != None: debug_string += ' Objects: ' + str(objects) if locale: debug_string += ' File: ' + str(inspect.getouterframes(current)[1][1]) print debug_string return