我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.getargvalues()。
def queue_exc(*arg, **kw): # pylint: disable=W0613 """Queue undefined variable exception""" _self = arg[0] if not isinstance(_self, AnsibleUndefinedVariable): # Run for AnsibleUndefinedVariable instance return _rslt_q = None for stack_trace in inspect.stack(): # Check if method to be skipped if stack_trace[3] in SKIP_METHODS: continue _frame = stack_trace[0] _locals = inspect.getargvalues(_frame).locals if 'self' not in _locals: continue # Check if current frame instance of worker if isinstance(_locals['self'], WorkerProcess): # Get queue to add exception _rslt_q = getattr(_locals['self'], '_rslt_q') if not _rslt_q: raise ValueError("No Queue found.") _rslt_q.put({"undefined_var": arg[3].message}, interceptor=True)
def _get_frame_args(frame): """Get the formatted arguments and class (if available) for a frame""" arginfo = inspect.getargvalues(frame) try: if not arginfo.args: return '', None # There have been reports from the field of python 2.6 which doesn't # return a namedtuple here but simply a tuple so fallback gracefully if # args isn't present. except AttributeError: return '', None firstarg = arginfo.args[0] if firstarg == 'self': self = arginfo.locals['self'] cls = self.__class__.__name__ arginfo.args.pop(0) del arginfo.locals['self'] else: cls = None formatted = inspect.formatargvalues(*arginfo) return formatted, cls
def _calling_instance_method_name_and_args(frame_level = 0): clazz = '' caller_args = [] method_name = '' frame = NamedLogger._calling_frame(frame_level + 1) frame_info = inspect.getframeinfo(frame) method_name = frame_info[2] args, _, _, values = inspect.getargvalues(frame) if len(args) and args[0] == 'self': instance = values.get('self', None) caller_args = map(lambda arg: values[arg], args) return (instance, method_name, caller_args)
def __init__(self, log_learn_rate = -5., log_init_scale = -6., fp_length = 10, other_param_dict = {'num_epochs' : 100, 'batch_size' : 200, 'normalize' : 1, 'dropout' : 0,# 'fp_length': 10, 'fp_depth': 3, 'activation' :relu, 'fp_type' : 'morgan', 'h1_size' : 100, 'conv_width': 20, 'num_outputs': 17, 'init_bias': 0.85}): #log_l1_penalty= 10e-5, log_l2_penalty= 10e-5): args, _, _, values = inspect.getargvalues(inspect.currentframe()) for arg, val in values.items(): setattr(self, arg, val)
def detect_scopes(): scopes = [] current_frame = inspect.currentframe() while current_frame is not None: if current_frame.f_code.co_name == 'logging_scope': scopes.append(current_frame.f_locals['name']) else: argvalues = inspect.getargvalues(current_frame) if 'self' in argvalues.args and getattr(argvalues.locals['self'].__class__, 'AUTO_LOGGING_SCOPE', False): scopes.append(argvalues.locals['self']) current_frame = current_frame.f_back out_scopes = [] seen = set() for scope in scopes[::-1]: if scope not in seen: out_scopes.append(scope if isinstance(scope, six.string_types) else (scope.name or scope.__class__.__name__)) seen.add(scope) return out_scopes
def frameInfo(self, fr): filename = fr.f_code.co_filename funcname = fr.f_code.co_name lineno = fr.f_lineno callfr = sys._getframe(3) callline = "%s %d" % (callfr.f_code.co_name, callfr.f_lineno) args, _, _, value_dict = inspect.getargvalues(fr) if len(args) and args[0] == 'self': instance = value_dict.get('self', None) if instance is not None: cls = getattr(instance, '__class__', None) if cls is not None: funcname = cls.__name__ + "." + funcname return "%s: %s %s: %s" % (callline, filename, lineno, funcname)
def parameters(only=None, exclude=None, ignore='self'): """Returns a dictionary of the calling functions parameter names and values. The optional arguments can be used to filter the result: only use this to only return parameters from this list of names. exclude use this to return every parameter *except* those included in this list of names. ignore use this inside methods to ignore the calling object's name. For convenience, it ignores 'self' by default. """ import inspect args, varargs, varkw, defaults = \ inspect.getargvalues(inspect.stack()[1][0]) if only is None: only = args[:] if varkw: only.extend(defaults[varkw].keys()) defaults.update(defaults[varkw]) if exclude is None: exclude = [] exclude.append(ignore) return dict([(attrname, defaults[attrname]) for attrname in only if attrname not in exclude])
def printCallSequenceRawData(deep=1): if deep is None or deep == 0: deep=1 deep = abs(deep) frames = getFrames(deep) print "\033[36m%s:%s" %(frames[0].f_code.co_filename, frames[0].f_code.co_firstlineno), for x in range(0,len(frames)): if not x: print "\033[96m%s \033[33m%s" %(frames[x].f_code.co_name, inspect.getargvalues(frames[x])) else: print "\033[94m<-- \033[95m%s(%s:%s)\033[33m%s" %(frames[x].f_code.co_name, frames[x].f_code.co_filename.split("/")[-1], frames[x].f_lineno, inspect.getargvalues(frames[x])) print "\033[0m", del frames
def get_local_arguments(fun, is_method=False): """Return the callers arguments and non-default keyword arguments. Args: fun: The function or method that is calling get_local_arguments. is_method: True if this is a method with a self argument. Returns: A tuple of (list of arguments, list of non default keyword arguments) """ frame = inspect.currentframe().f_back argvals = inspect.getargvalues(frame) argspec = inspect.getargspec(fun) lvals = argvals.locals num_args = len(argspec.args) - len(argspec.defaults) arg_names = argspec.args[0:num_args] kwarg_names = argspec.args[num_args:] args = [lvals[k] for k in arg_names] kwargs_a = [(k, lvals[k], d) for (k, d) in zip(kwarg_names, argspec.defaults)] kwargs = [(k, v) for (k, v, d) in kwargs_a if v != d] if is_method: args = args[1:] # strip off the self argument return (args, kwargs)
def logFunctionAndArgs(): 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") logging.info("--> "+functionName+'('+output+')')
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 hook(self): '''Magic to hook various function calls in sslstrip''' #gets the function name and args of our caller frame = sys._getframe(1) fname = frame.f_code.co_name keys,_,_,values = inspect.getargvalues(frame) #assumes that no one calls del on an arg :-/ args = {} for key in keys: args[key] = values[key] #prevent self conflict if (fname == "handleResponse") or (fname == "handleHeader") or (fname == "handleEndHeaders"): args['request'] = args['self'] args['response'] = args['self'].client else: args['request'] = args['self'] del args['self'] log.debug("hooking {}()".format(fname)) #calls any plugin that has this hook try: if self.plugin_mthds: for f in self.plugin_mthds[fname]: a = f(**args) if a != None: args = a except Exception as e: #This is needed because errors in hooked functions won't raise an Exception + Traceback (which can be infuriating) log.error("Exception occurred in hooked function") traceback.print_exc() #pass our changes to the locals back down return args
def _get_args_from_frame(frames, frame_num): if len(frames) > frame_num and frames[frame_num] and frames[frame_num][0]: argvalues = inspect.getargvalues(frames[frame_num][0]) formated_args = inspect.formatargvalues(*argvalues) # remove the first 'self' arg from the log as it adds no information formated_args = re.sub(r'\(self=.*?, ', "(", formated_args) return formated_args
def pass_keywords(): """ Helper function that extracts the arguments of the callee (must be a (class) method) and returns them. Credits to `Kelly Yancey <http://kbyanc.blogspot.de/2007/07/python-aggregating-function-arguments.html>`_ """ args, _, _, locals = inspect.getargvalues(inspect.stack()[1][0]) args.pop(0) kwargs = {i: j for i, j in locals.items() if i in args} return kwargs
def get_property(cls, obj, prop): ''' :param obj: :param prop: :return: ''' args, varargs, keywords, locals = inspect.getargvalues(inspect.currentframe()) print(args, varargs, keywords, locals)
def get_class_from_frame(fr): args, _, _, value_dict = inspect.getargvalues(fr) if len(args) and args[0] == 'self': instance = value_dict.get('self', None) if instance: return getattr(instance, '__class__', None) return None
def test_frame(self): args, varargs, varkw, locals = inspect.getargvalues(mod.fr) self.assertEqual(args, ['x', 'y']) self.assertEqual(varargs, None) self.assertEqual(varkw, None) self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14}) self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), '(x=11, y=14)')
def test_previous_frame(self): args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back) self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f']) self.assertEqual(varargs, 'g') self.assertEqual(varkw, 'h') self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), '(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})')
def test_previous_frame(self): args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back) self.assertEqual(args, ['a', 'b', 'c', 'd', ['e', ['f']]]) self.assertEqual(varargs, 'g') self.assertEqual(varkw, 'h') self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals), '(a=7, b=8, c=9, d=3, (e=4, (f=5,)), *g=(), **h={})')
def debug(message): outerFrame = getouterframes(currentframe())[1][0] (args, _, _, values) = getargvalues(outerFrame) argsValue = '' for i in args: if i is 'self': continue argsValue += "(%s=%s)" % (i, str(values[i])) stack = extract_stack() (filename, line, procname, text) = stack[-2] LOGGER.debug(str(filename) + ' ' + str(procname) + str(argsValue) + ':' + str(line) + '> ' + str(message))
def func(a, b, c): frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) for i in args: print " %s = %s" % (i, values[i]) return [(i, values[i]) for i in args]
def __enter__(self): _, _, _, env_locals = inspect.getargvalues(inspect.currentframe( ).f_back) self.__dict__['_env_locals'] = env_locals.keys()
def __exit__(self, type, value, traceback): _, _, _, env_locals = inspect.getargvalues(inspect.currentframe( ).f_back) prev_env_locals = self.__dict__['_env_locals'] del self.__dict__['_env_locals'] for k in env_locals.keys(): if k not in prev_env_locals: self.__setattr__(k, env_locals[k]) env_locals[k] = self.__getattr__(k) return True
def __init__(self, frame, name=None): self.code = c = frame.f_code self.filename = c.co_filename self.lineno = c.co_firstlineno self.name = name or c.co_name # builtin methods report as name <method '...' of '...' objects> # Extract their real name from that. if self.name.startswith('<method '): self.name = self.name.split("'", 3)[1] arg_info = inspect.getargvalues(frame) args=[] # There are cases where we can't generate a signature... no_signature=False if arg_info: for a in arg_info.args: # FIXME: There are cases where we don't know how to handle arguments. # If 'a' is a list, we bail out... if type(a) is list: no_signature=True break else: v = arg_info.locals.get(a, None) if type(v) == numpy.ndarray: t = 'ndarray(dtype=%s, shape=%s)'%(v.dtype, v.shape) # cython-compiled code doesn't report a locals dict, so 'v' may be None elif v is None: t = '<unknown>' else: t = str(type(v).__name__) args.append((a, t)) self.args = no_signature and None or tuple(args)
def hook(self): '''Magic to hook various function calls in sslstrip''' #gets the function name and args of our caller frame = sys._getframe(1) fname = frame.f_code.co_name keys,_,_,values = inspect.getargvalues(frame) #assumes that no one calls del on an arg :-/ args = {} for key in keys: args[key] = values[key] #prevent self conflict if (fname == "handleResponse") or (fname == "handleHeader") or (fname == "handleEndHeaders"): args['request'] = args['self'] args['response'] = args['self'].client else: args['request'] = args['self'] del args['self'] log.debug("hooking {}()".format(fname)) #calls any plugin that has this hook try: for f in self.plugin_mthds[fname]: a = f(**args) if a != None: args = a except Exception as e: #This is needed because errors in hooked functions won't raise an Exception + Traceback (which can be infuriating) log.error("Exception occurred in hooked function") traceback.print_exc() #pass our changes to the locals back down return args
def update_auth_settings(resource_group_name, name, enabled=None, action=None, # pylint: disable=unused-argument client_id=None, token_store_enabled=None, # pylint: disable=unused-argument runtime_version=None, token_refresh_extension_hours=None, # pylint: disable=unused-argument allowed_external_redirect_urls=None, client_secret=None, # pylint: disable=unused-argument allowed_audiences=None, issuer=None, facebook_app_id=None, # pylint: disable=unused-argument facebook_app_secret=None, facebook_oauth_scopes=None, # pylint: disable=unused-argument twitter_consumer_key=None, twitter_consumer_secret=None, # pylint: disable=unused-argument google_client_id=None, google_client_secret=None, # pylint: disable=unused-argument google_oauth_scopes=None, microsoft_account_client_id=None, # pylint: disable=unused-argument microsoft_account_client_secret=None, # pylint: disable=unused-argument microsoft_account_oauth_scopes=None, slot=None): # pylint: disable=unused-argument auth_settings = get_auth_settings(resource_group_name, name, slot) if action == 'AllowAnonymous': auth_settings.unauthenticated_client_action = UnauthenticatedClientAction.allow_anonymous elif action: auth_settings.unauthenticated_client_action = UnauthenticatedClientAction.redirect_to_login_page auth_settings.default_provider = AUTH_TYPES[action] import inspect frame = inspect.currentframe() bool_flags = ['enabled', 'token_store_enabled'] # note: getargvalues is used already in azure.cli.core.commands. # and no simple functional replacement for this deprecating method for 3.5 args, _, _, values = inspect.getargvalues(frame) # pylint: disable=deprecated-method for arg in args[2:]: print(arg, values[arg]) if values.get(arg, None): setattr(auth_settings, arg, values[arg] if arg not in bool_flags else values[arg] == 'true') return _generic_site_operation(resource_group_name, name, 'update_auth_settings', slot, auth_settings)
def update_site_configs(resource_group_name, name, slot=None, linux_fx_version=None, php_version=None, python_version=None, # pylint: disable=unused-argument net_framework_version=None, # pylint: disable=unused-argument java_version=None, java_container=None, java_container_version=None, # pylint: disable=unused-argument remote_debugging_enabled=None, web_sockets_enabled=None, # pylint: disable=unused-argument always_on=None, auto_heal_enabled=None, # pylint: disable=unused-argument use32_bit_worker_process=None, # pylint: disable=unused-argument app_command_line=None): # pylint: disable=unused-argument configs = get_site_configs(resource_group_name, name, slot) if linux_fx_version: if linux_fx_version.strip().lower().startswith('docker|'): update_app_settings(resource_group_name, name, ["WEBSITES_ENABLE_APP_SERVICE_STORAGE=false"]) else: delete_app_settings(resource_group_name, name, ["WEBSITES_ENABLE_APP_SERVICE_STORAGE"]) import inspect frame = inspect.currentframe() bool_flags = ['remote_debugging_enabled', 'web_sockets_enabled', 'always_on', 'auto_heal_enabled', 'use32_bit_worker_process'] # note: getargvalues is used already in azure.cli.core.commands. # and no simple functional replacement for this deprecating method for 3.5 args, _, _, values = inspect.getargvalues(frame) # pylint: disable=deprecated-method for arg in args[3:]: if values.get(arg, None): setattr(configs, arg, values[arg] if arg not in bool_flags else values[arg] == 'true') return _generic_site_operation(resource_group_name, name, 'update_configuration', slot, configs)
def __init__(self, current_frame): """ Init the MetaPrameterRecord with "Agent" parameters by passing inspect.currentframe() from Agent Class The Init will search back to find the parent class to capture all passed parameters and store them in "self.meta_params". NOTE: Currently only optimized for TensorBoard output TODO: Add JSON Export, TEXT EXPORT Args: current_frame: frame value from class to obtain metaparameters[= inspect.currentframe()] """ self.ignore_unknown_dtypes = False self.meta_params = dict() self.method_calling = inspect.getframeinfo(current_frame)[2] _, _, __, self.vals_current = inspect.getargvalues(current_frame) # self is the class name of the frame involved if 'self' in self.vals_current: self.recorded_class_type = self.vals_current['self'] # Add explicit AgentName item so class can be deleted self.meta_params['AgentName'] = str(self.vals_current['self']) frame_list = inspect.getouterframes(current_frame) for frame in frame_list: # Rather than frame.frame (named tuple), use [0] for python2 args, varargs, keywords, vals =inspect.getargvalues(frame[0]) if 'self' in vals: if self.recorded_class_type == vals['self']: for i in args: self.meta_params[i] = vals[i] # Remove the "CLASS" from the dictionary, has no value "AgentName" contains STR of Class del self.meta_params['self']
def hook(self): '''Magic to hook various function calls in sslstrip''' #gets the function name and args of our caller frame = sys._getframe(1) fname = frame.f_code.co_name keys,_,_,values = inspect.getargvalues(frame) #assumes that no one calls del on an arg :-/ args = {} for key in keys: args[key] = values[key] #prevent self conflict args['request'] = args['self'] del args['self'] #calls any plugin that has this hook try: for f in self.pmthds[fname]: a = f(**args) if a != None: args = a except KeyError: pass #pass our changes to the locals back down return args
def node_workspace_exists(func): @wraps(func) def wrapper(*args, **kwargs): frame = inspect.currentframe() frame_args, _, _, values = inspect.getargvalues(frame) node_name = values["args"][1] if not Workspace.check_workspace_exists(node_name): print "Node {} runtime workspace doesn't exist".format(node_name) logger_cmd.warning("cmd res: Node {} runtime workspace doesn't exist".format(node_name)) return return func(*args, **kwargs) return wrapper
def traceargs(): frame = inspect.currentframe() args, _, _, values = inspect.getargvalues(frame) for i in args: print " %s:\n%s" % (i, pprint.pformat(values[i]))
def get_current_func_arg_name_values(): """Return a dict of {parameter name: value} of current function. """ caller_frame = inspect.currentframe().f_back arg_info = inspect.getargvalues(caller_frame) params = { key: arg_info.locals[key] for key in arg_info.args if key != 'self' } if arg_info.varargs: params[arg_info.varargs] = arg_info.locals[arg_info.varargs] if arg_info.keywords: params.update(arg_info.locals[arg_info.keywords]) return params
def MT2bl_wrapper(lepE, lepPx, lepPy, lepPz, b1E, b1Px, b1Py, b1Pz, b2E, b2Px, b2Py, b2Pz, MET_x, MET_y): code = """ double pl[4] = { lepE, lepPx, lepPy, lepPz}; // El, plx, ply, plz, (visible lepton) double pb1[4] = { b1E, b1Px, b1Py, b1Pz }; // Eb1, pb1x, pb1y, pb1z (bottom on the same side as the visible lepton) double pb2[4] = { b2E, b2Px, b2Py, b2Pz }; // Eb2, pb2x, pb2y, pb2z (other bottom, paired with the invisible W) double pmiss[3] = { 0., MET_x, MET_y }; // <unused>, pmx, pmy (missing pT) mt2bl_bisect::mt2bl mt2bl; mt2bl.set_momenta(pl, pb1, pb2, pmiss); return_val = mt2bl.get_mt2bl(); """ # Pass all Python arguments to C++ frame = inspect.currentframe() args = inspect.getargvalues(frame)[0] lib_MT2bl = inline(code,args, headers=['"MT2bl.h"'], include_dirs=["/scratch18/kazuki2/analyses/mT2_packages"], verbose=0 ) return lib_MT2bl
def MT2_wrapper(m1, p1x, p1y, m2, p2x, p2y, MET_m, MET_x, MET_y): code = """ mt2_bisect::mt2 mt2_event;; double pa[3] = { m1, p1x, p1y }; double pb[3] = { m2, p2x, p2y }; double pmiss[3] = { 0, MET_x, MET_y }; double mn = MET_m; mt2_event.set_momenta(pa,pb,pmiss); mt2_event.set_mn(mn); //mt2_event.print(); const double mt2 = mt2_event.get_mt2(); // std::cout << endl << " mt2 = " << mt2 << std::endl; return_val = mt2; """ # Pass all Python arguments to C++ frame = inspect.currentframe() args = inspect.getargvalues(frame)[0] # print(args) lib_MT2 = inline(code,args, headers=['"mt2_bisect.h"','"mt2_bisect_main.h"'], include_dirs=["/scratch18/kazuki2/analyses/mT2_packages"], verbose=0 ) return lib_MT2