我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用inspect.getouterframes()。
def _called_from_setup(run_frame): """ Attempt to detect whether run() was called from setup() or by another command. If called by setup(), the parent caller will be the 'run_command' method in 'distutils.dist', and *its* caller will be the 'run_commands' method. If called any other way, the immediate caller *might* be 'run_command', but it won't have been called by 'run_commands'. Return True in that case or if a call stack is unavailable. Return False otherwise. """ if run_frame is None: msg = "Call stack not available. bdist_* commands may fail." warnings.warn(msg) if platform.python_implementation() == 'IronPython': msg = "For best results, pass -X:Frames to enable call stack." warnings.warn(msg) return True res = inspect.getouterframes(run_frame)[2] caller, = res[:1] info = inspect.getframeinfo(caller) caller_module = caller.f_globals.get('__name__', '') return ( caller_module == 'distutils.dist' and info.function == 'run_commands' )
def meld(got, expected): if got == expected: return import inspect call_frame = inspect.getouterframes(inspect.currentframe(), 2) test_name = call_frame[1][3] from pprint import pformat import os from os import path os.makedirs(test_name, exist_ok=True) got_fn = path.join(test_name, 'got') expected_fn = path.join(test_name, 'expected') with open(got_fn, 'w') as got_f, open(expected_fn, 'w') as expected_f: got_f.write(pformat(got)) expected_f.write(pformat(expected)) import subprocess subprocess.run(['meld', got_fn, expected_fn])
def __call__(self, name, func=None): (frame, filename, line_number, function_name, lines, index) = inspect.getouterframes(inspect.currentframe())[1] caller="%s.%s(%s)" % (filename, function_name, line_number) self.show("%s %s" % (self.msg, caller)) #print("Showing....", self.msg, caller) if func==None: method=name else: method=func @wraps(method) def wrapper(*args, **kwargs): result=method(*args, **kwargs) return result return wrapper
def __init__(self, context=None, **kwargs): """ When creating the placeholder, a process-specific context should be given. Parameters ---------- context : str Context is used to indicate the process that generated the processing statistics. Returns ------- Metrics Instance where processing statistics can be added or modified. """ # If context is not given, determine it from calling function. if context is None: previous_frame = inspect.getouterframes(inspect.currentframe())[1] module = inspect.getmodulename(previous_frame[1]) context = module + '.' + previous_frame[3] self.context = context for arg, value in kwargs.items(): setattr(self, arg, value)
def async_calling_function(callFrame): def calling_functionn(__function): """ View Calling Function to debug """ def wrapper(*args, **kwargs): cur_frame = inspect.currentframe() cal_frame = inspect.getouterframes(cur_frame, callFrame) stack = [] for t in cal_frame: if 'Yu-gi' in t[1]: stack.append(t[3]) logger.debug("Called by: " + str(stack)) return __function(*args, **kwargs) return wrapper return calling_functionn
def getFunctionCall(idx=1): """Returns the name of function or method that was called idx frames outwards. .. note:: ``idx=0`` will of course return ``getFunctionCall``. Args: idx (int): Steps outwards. Returns: str: Name of function or method. """ frame = inspect.currentframe() try: return inspect.getouterframes(frame)[idx][3] except IndexError: return ""
def _add_served_directory(cls, config, relative_path, config_var): ''' Add extra public/template directories to config. ''' import inspect import os assert config_var in ('extra_template_paths', 'extra_public_paths') # we want the filename that of the function caller but they will # have used one of the available helper functions frame, filename, line_number, function_name, lines, index =\ inspect.getouterframes(inspect.currentframe())[2] this_dir = os.path.dirname(filename) absolute_path = os.path.join(this_dir, relative_path) if absolute_path not in config.get(config_var, ''): if config.get(config_var): config[config_var] += ',' + absolute_path else: config[config_var] = absolute_path
def _add_resource(cls, path, name): '''Add a Fanstatic resource library to CKAN. Fanstatic libraries are directories containing static resource files (e.g. CSS, JavaScript or image files) that can be accessed from CKAN. See :doc:`/theming/index` for more details. ''' import inspect import os # we want the filename that of the function caller but they will # have used one of the available helper functions frame, filename, line_number, function_name, lines, index =\ inspect.getouterframes(inspect.currentframe())[1] this_dir = os.path.dirname(filename) absolute_path = os.path.join(this_dir, path) import ckan.lib.fanstatic_resources ckan.lib.fanstatic_resources.create_library(name, absolute_path)
def parse(source: str, globals_=None, locals_=None, ast_module=typed_ast.ast3, *args, **kwargs): """Act like ast_module.parse() but also put static type info into AST.""" if globals_ is None or locals_ is None: frame_info = inspect.getouterframes(inspect.currentframe())[1] caller_frame = frame_info[0] if globals_ is None: globals_ = caller_frame.f_globals if locals_ is None: locals_ = caller_frame.f_locals tree = ast_module.parse(source, *args, **kwargs) _LOG.debug('%s', ast_module.dump(tree)) tree = augment(tree, globals_, locals_, ast_module) _LOG.debug('%s', ast_module.dump(tree)) return tree
def enable_debug(): if IS_PYPY: sys.stderr.write("settrace api unsupported on pypy") sys.stderr.flush() return import inspect def trace_green(event, args): src, target = args if event == "switch": print("from %s switch to %s" % (src, target)) elif event == "throw": print("from %s throw exception to %s" % (src, target)) if src.gr_frame: tracebacks = inspect.getouterframes(src.gr_frame) buff = [] for traceback in tracebacks: srcfile, lineno, func_name, codesample = traceback[1:-1] trace_line = '''File "%s", line %d, in %s\n%s ''' buff.append(trace_line % (srcfile, lineno, func_name, "".join(codesample))) print("".join(buff)) greenlet.settrace(trace_green)
def saveSetting(key, value): """ Each toolbox is assigned a settings file in the settings folder at the .hfx level. This allows the toolbox to save data pertaining to itself that must persist. """ curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) callerLocation = os.path.dirname(calframe[1][1]) settingsPath = loadSettings(callerLocation) with open(settingsPath, 'r') as settingsFile: settings = json.loads(settingsFile.read()) settings[key] = value with open(settingsPath, 'w') as settingsFile: settingsFile.write(json.dumps(settings))
def loadSetting(key, default=None): """ Each toolbox is assigned a settings file in the settings folder at the .hfx level. This allows the toolbox to save data pertaining to itself that must persist. """ curframe = inspect.currentframe() calframe = inspect.getouterframes(curframe, 2) callerLocation = os.path.dirname(calframe[1][1]) settingsPath = loadSettings(callerLocation) with open(settingsPath, 'r') as settingsFile: settings = json.loads(settingsFile.read()) try: return settings[key] except KeyError: return default