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)
python类getargvalues()的实例源码
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)
fp1_reaction_estimator.py 文件源码
项目:neural_reaction_fingerprint
作者: jnwei
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
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)
fp1_double_reaction_estimator.py 文件源码
项目:neural_reaction_fingerprint
作者: jnwei
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
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)
fp1_reaction_estimator.py 文件源码
项目:neural_reaction_fingerprint
作者: jnwei
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
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 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 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 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_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 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