Python sys._getframe() Examples
The following are 30 code examples for showing how to use sys._getframe(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
sys
, or try the search function
.
Example 1
Project: ssm-cache-python Author: alexcasalboni File: versioning_test.py License: MIT License | 7 votes |
def test_update_versions(self): """ Test version update """ method_name = sys._getframe().f_code.co_name self._setUp(method_name) name = method_name self._create_or_update_param(name) param = SSMParameter(name) self.assertEqual(param.version, 1) self.assertEqual(param.value, self.PARAM_VALUE) # this will update the value and create version 2 self._create_or_update_param(name, self.PARAM_VALUE_V2) param.refresh() # refreshing should give you version 2 self.assertEqual(param.version, 2) self.assertEqual(param.value, self.PARAM_VALUE_V2) self._delete_param(name)
Example 2
Project: ssm-cache-python Author: alexcasalboni File: versioning_test.py License: MIT License | 6 votes |
def test_select_versions(self): """ Test version selection """ method_name = sys._getframe().f_code.co_name self._setUp(method_name) name = method_name self._create_or_update_param(name) param = SSMParameter("%s:1" % name) self.assertEqual(param.value, self.PARAM_VALUE) self.assertEqual(param.version, 1) # this will update the value and create version 2 self._create_or_update_param(name, self.PARAM_VALUE_V2) param.refresh() self.assertEqual(param.value, self.PARAM_VALUE) self.assertEqual(param.version, 1) self._delete_param(name)
Example 3
Project: ssm-cache-python Author: alexcasalboni File: versioning_test.py License: MIT License | 6 votes |
def test_versions_group(self): """ Test version update in a group """ method_name = sys._getframe().f_code.co_name self._setUp(method_name) name = method_name self._create_or_update_param(name) group = SSMParameterGroup() param = group.parameter(name) self.assertEqual(param.version, 1) self.assertEqual(param.value, self.PARAM_VALUE) # this will update the value and create version 2 self._create_or_update_param(name, self.PARAM_VALUE_V2) group.refresh() # refreshing should give you version 2 self.assertEqual(param.version, 2) self.assertEqual(param.value, self.PARAM_VALUE_V2) self._delete_param(name)
Example 4
Project: ssm-cache-python Author: alexcasalboni File: versioning_test.py License: MIT License | 6 votes |
def test_versions_group_select(self): """ Test version selection in a group """ method_name = sys._getframe().f_code.co_name self._setUp(method_name) name = method_name self._create_or_update_param(name) # this will update the value and create version 2 self._create_or_update_param(name, self.PARAM_VALUE_V2) group = SSMParameterGroup() param = group.parameter("%s:1" % name) self.assertEqual(param.version, 1) self.assertEqual(param.value, self.PARAM_VALUE) self._delete_param(name)
Example 5
Project: Paradrop Author: ParadropLabs File: output.py License: Apache License 2.0 | 6 votes |
def silentLogPrefix(stepsUp): ''' logPrefix v2-- gets caller information silently (without caller intervention) The single parameter reflects how far up the stack to go to find the caller and depends how deep the direct caller to this method is wrt to the target caller NOTE: Some calls cannot be silently prefixed (getting into the twisted code is a great example) :param stepsUp: the number of steps to move up the stack for the caller :type steps: int. ''' try: trace = sys._getframe(stepsUp).f_code.co_filename line = sys._getframe(stepsUp).f_lineno module, package = parseLogPrefix(trace) except: return 'unknown', 'unknown', '??' return package, module, line
Example 6
Project: aws-ops-automator Author: awslabs File: __init__.py License: Apache License 2.0 | 6 votes |
def get_extended_info(error_message, prefix): # noinspection PyProtectedMember caller_stack_frame = sys._getframe(2) caller = caller_stack_frame.f_code.co_name line = caller_stack_frame.f_lineno module = inspect.getmodule(caller_stack_frame) error_code = get_error_constant_name(module.__dict__, error_message, prefix) if error_code is None: error_code = get_error_constant_name(caller_stack_frame.f_globals, error_message, prefix) result = { "Caller": caller, "Module": module.__name__, "Line": line } if error_code is not None: result["Code"] = error_code return result
Example 7
Project: jawfish Author: war-and-code File: __init__.py License: MIT License | 6 votes |
def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise Exception except: return sys.exc_info()[2].tb_frame.f_back # _srcfile is only used in conjunction with sys._getframe(). # To provide compatibility with older versions of Python, set _srcfile # to None if _getframe() is not available; this value will prevent # findCaller() from being called. #if not hasattr(sys, "_getframe"): # _srcfile = None # #_startTime is used as the base when calculating the relative time of events #
Example 8
Project: OpenTrader Author: OpenTrading File: tools.py License: GNU Lesser General Public License v3.0 | 6 votes |
def set_trace(): """Call pdb.set_trace in the caller's frame. First restore sys.stdout and sys.stderr. Note that the streams are NOT reset to whatever they were before the call once pdb is done! """ import pdb for stream in 'stdout', 'stderr': output = getattr(sys, stream) orig_output = getattr(sys, '__%s__' % stream) if output != orig_output: # Flush the output before entering pdb if hasattr(output, 'getvalue'): orig_output.write(output.getvalue()) orig_output.flush() setattr(sys, stream, orig_output) exc, tb = sys.exc_info()[1:] if tb: if isinstance(exc, AssertionError) and exc.args: # The traceback is not printed yet print_exc() pdb.post_mortem(tb) else: pdb.Pdb().set_trace(sys._getframe().f_back)
Example 9
Project: OpenTrader Author: OpenTrading File: cmd2plus.py License: GNU Lesser General Public License v3.0 | 6 votes |
def set_trace(): """Call pdb.set_trace in the caller's frame. First restore sys.stdout and sys.stderr. Note that the streams are NOT reset to whatever they were before the call once pdb is done! """ import pdb for stream in 'stdout', 'stderr': output = getattr(sys, stream) orig_output = getattr(sys, '__%s__' % stream) if output != orig_output: # Flush the output before entering pdb if hasattr(output, 'getvalue'): orig_output.write(output.getvalue()) orig_output.flush() setattr(sys, stream, orig_output) exc, tb = sys.exc_info()[1:] if tb: if isinstance(exc, AssertionError) and exc.args: # The traceback is not printed yet print_exc() pdb.post_mortem(tb) else: pdb.Pdb().set_trace(sys._getframe().f_back)
Example 10
Project: DidYouMean-Python Author: SylvainDe File: didyoumean_internal_tests.py License: MIT License | 6 votes |
def name_corresponds_to(self, name, expected): """Helper functions to test get_objects_in_frame. Check that the name corresponds to the expected objects (and their scope) in the frame of calling function. None can be used to match any object as it can be hard to describe an object when it is hidden by something in a closer scope. Also, extra care is to be taken when calling the function because giving value by names might affect the result (adding in local scope). """ frame = sys._getframe(1) # frame of calling function lst = get_objects_in_frame(frame).get(name, []) self.assertEqual(len(lst), len(expected)) for scopedobj, exp in zip(lst, expected): obj, scope = scopedobj expobj, expscope = exp self.assertEqual(scope, expscope, name) if expobj is not None: self.assertEqual(obj, expobj, name)
Example 11
Project: verge3d-blender-addon Author: Soft8Soft File: support.py License: GNU General Public License v3.0 | 6 votes |
def requires(resource, msg=None): """Raise ResourceDenied if the specified resource is not available. If the caller's module is __main__ then automatically return True. The possibility of False being returned occurs when regrtest.py is executing. """ if resource == 'gui' and not _is_gui_available(): raise unittest.SkipTest("Cannot use the 'gui' resource") # see if the caller's module is __main__ - if so, treat as if # the resource was set if sys._getframe(1).f_globals.get("__name__") == "__main__": return if not is_resource_enabled(resource): if msg is None: msg = "Use of the %r resource not enabled" % resource raise ResourceDenied(msg)
Example 12
Project: misp42splunk Author: remg427 File: decorator.py License: GNU Lesser General Public License v3.0 | 6 votes |
def update(self, func, **kw): "Update the signature of func with the data in self" func.__name__ = self.name func.__doc__ = getattr(self, 'doc', None) func.__dict__ = getattr(self, 'dict', {}) func.__defaults__ = self.defaults func.__kwdefaults__ = self.kwonlydefaults or None func.__annotations__ = getattr(self, 'annotations', None) try: frame = sys._getframe(3) except AttributeError: # for IronPython and similar implementations callermodule = '?' else: callermodule = frame.f_globals.get('__name__', '?') func.__module__ = getattr(self, 'module', callermodule) func.__dict__.update(kw)
Example 13
Project: misp42splunk Author: remg427 File: decorator.py License: GNU Lesser General Public License v3.0 | 6 votes |
def update(self, func, **kw): "Update the signature of func with the data in self" func.__name__ = self.name func.__doc__ = getattr(self, 'doc', None) func.__dict__ = getattr(self, 'dict', {}) func.__defaults__ = self.defaults func.__kwdefaults__ = self.kwonlydefaults or None func.__annotations__ = getattr(self, 'annotations', None) try: frame = sys._getframe(3) except AttributeError: # for IronPython and similar implementations callermodule = '?' else: callermodule = frame.f_globals.get('__name__', '?') func.__module__ = getattr(self, 'module', callermodule) func.__dict__.update(kw)
Example 14
Project: tornado-zh Author: tao12345666333 File: web.py License: MIT License | 6 votes |
def render_string(self, template_name, **kwargs): """使用给定的参数生成指定模板. 我们返回生成的字节字符串(以utf8). 为了生成并写一个模板 作为响应, 使用上面的render(). """ # If no template_path is specified, use the path of the calling file template_path = self.get_template_path() if not template_path: frame = sys._getframe(0) web_file = frame.f_code.co_filename while frame.f_code.co_filename == web_file: frame = frame.f_back template_path = os.path.dirname(frame.f_code.co_filename) with RequestHandler._template_loader_lock: if template_path not in RequestHandler._template_loaders: loader = self.create_template_loader(template_path) RequestHandler._template_loaders[template_path] = loader else: loader = RequestHandler._template_loaders[template_path] t = loader.load(template_name) namespace = self.get_template_namespace() namespace.update(kwargs) return t.generate(**namespace)
Example 15
Project: tornado-zh Author: tao12345666333 File: web.py License: MIT License | 6 votes |
def render_string(self, template_name, **kwargs): """使用给定的参数生成指定模板. 我们返回生成的字节字符串(以utf8). 为了生成并写一个模板 作为响应, 使用上面的render(). """ # If no template_path is specified, use the path of the calling file template_path = self.get_template_path() if not template_path: frame = sys._getframe(0) web_file = frame.f_code.co_filename while frame.f_code.co_filename == web_file: frame = frame.f_back template_path = os.path.dirname(frame.f_code.co_filename) with RequestHandler._template_loader_lock: if template_path not in RequestHandler._template_loaders: loader = self.create_template_loader(template_path) RequestHandler._template_loaders[template_path] = loader else: loader = RequestHandler._template_loaders[template_path] t = loader.load(template_name) namespace = self.get_template_namespace() namespace.update(kwargs) return t.generate(**namespace)
Example 16
Project: py Author: pytest-dev File: _assertionold.py License: MIT License | 6 votes |
def check(s, frame=None): if frame is None: frame = sys._getframe(1) frame = py.code.Frame(frame) expr = parse(s, 'eval') assert isinstance(expr, ast.Expression) node = Interpretable(expr.node) try: node.eval(frame) except passthroughex: raise except Failure: e = sys.exc_info()[1] report_failure(e) else: if not frame.is_true(node.result): sys.stderr.write("assertion failed: %s\n" % node.nice_explanation()) ########################################################### # API / Entry points # #########################################################
Example 17
Project: py Author: pytest-dev File: warning.py License: MIT License | 6 votes |
def _apiwarn(startversion, msg, stacklevel=2, function=None): # below is mostly COPIED from python2.4/warnings.py's def warn() # Get context information if isinstance(stacklevel, str): frame = sys._getframe(1) level = 1 found = frame.f_code.co_filename.find(stacklevel) != -1 while frame: co = frame.f_code if co.co_filename.find(stacklevel) == -1: if found: stacklevel = level break else: found = True level += 1 frame = frame.f_back else: stacklevel = 1 msg = "%s (since version %s)" %(msg, startversion) warn(msg, stacklevel=stacklevel+1, function=function)
Example 18
Project: py Author: pytest-dev File: test_code.py License: MIT License | 6 votes |
def test_frame_getargs(): def f1(x): return sys._getframe(0) fr1 = py.code.Frame(f1('a')) assert fr1.getargs(var=True) == [('x', 'a')] def f2(x, *y): return sys._getframe(0) fr2 = py.code.Frame(f2('a', 'b', 'c')) assert fr2.getargs(var=True) == [('x', 'a'), ('y', ('b', 'c'))] def f3(x, **z): return sys._getframe(0) fr3 = py.code.Frame(f3('a', b='c')) assert fr3.getargs(var=True) == [('x', 'a'), ('z', {'b': 'c'})] def f4(x, *y, **z): return sys._getframe(0) fr4 = py.code.Frame(f4('a', 'b', c='d')) assert fr4.getargs(var=True) == [('x', 'a'), ('y', ('b',)), ('z', {'c': 'd'})]
Example 19
Project: mlbv Author: kmac File: request.py License: GNU General Public License v3.0 | 5 votes |
def request_json(url, output_filename=None, cache_stale=None): """Sends a request expecting a json-formatted response. If output_filename is given, then the output is saved to file. This also enables basic caching, where cache_stale is the number of seconds since file is last modified before the cached file is considered stale (0 means disable the cache). """ cache_stale = _get_cache_stale_secs(cache_stale) # Guard against very long filenames: if output_filename and len(output_filename) >= MAX_CACHE_FILENAME_LEN: output_filename = output_filename[0:MAX_CACHE_FILENAME_LEN-1] if output_filename and cache_stale: if output_filename in CACHE: return CACHE[output_filename] json_file = os.path.join(_get_cachedir(), '{}.json'.format(output_filename)) if os.path.exists(json_file) and (int(time.time()) - os.path.getmtime(json_file) < cache_stale): with open(json_file) as jfh: CACHE[output_filename] = json.load(jfh) if config.DEBUG: LOG.info('Loaded from cache: %s', output_filename) return CACHE[output_filename] LOG.debug('Getting url=%s ...', url) headers = { 'User-Agent': config.CONFIG.ua_iphone, 'Connection': 'close' } util.log_http(url, 'get', headers, sys._getframe().f_code.co_name) response = requests.get(url, headers=headers, verify=config.VERIFY_SSL) response.raise_for_status() # Note: this fails on windows in some cases https://github.com/kennethreitz/requests-html/issues/171 if output_filename is not None or (config.DEBUG and config.SAVE_JSON_FILE): json_file = os.path.join(_get_cachedir(), '{}.json'.format(output_filename)) with open(json_file, 'w', encoding='utf-8') as out: # write date to json_file out.write(response.text) if cache_stale: LOG.debug('Caching url=%s, filename=%s', url, output_filename) CACHE[output_filename] = response.json() return CACHE[output_filename] return response.json()
Example 20
Project: ssm-cache-python Author: alexcasalboni File: versioning_test.py License: MIT License | 5 votes |
def test_versions_unexisting(self): """ Test non existing version """ method_name = sys._getframe().f_code.co_name self._setUp(method_name) name = method_name self._create_or_update_param(name) param = SSMParameter("%s:10" % name) with self.assertRaises(InvalidParameterError): print(param.value) self._delete_param(name)
Example 21
Project: QCElemental Author: MolSSI File: testing.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def tnm() -> str: """Returns the name of the calling function, usually name of test case. """ return sys._getframe().f_back.f_code.co_name
Example 22
Project: WorldsFirstSha2Vulnerability Author: laie File: sha256.py License: MIT License | 5 votes |
def update(self, m): if not m: return if type(m) is not str: raise TypeError, '%s() argument 1 must be string, not %s' % (sys._getframe().f_code.co_name, type(m).__name__) self._buffer += m self._counter += len(m) while len(self._buffer) >= 64: self._sha256_process(self._buffer[:64]) self._buffer = self._buffer[64:]
Example 23
Project: Depth-Map-Prediction Author: hjimce File: thutil.py License: GNU General Public License v3.0 | 5 votes |
def __init__(self, globals=None, locals=None): self.globals = globals or {} self.locals = locals or sys._getframe(1).f_locals
Example 24
Project: pycasbin Author: casbin File: test_model_benchmark.py License: Apache License 2.0 | 5 votes |
def get_function_name(): return sys._getframe(2).f_code.co_name
Example 25
Project: jawfish Author: war-and-code File: six.py License: MIT License | 5 votes |
def exec_(code, globs=None, locs=None): """Execute code in a namespace.""" if globs is None: frame = sys._getframe(1) globs = frame.f_globals if locs is None: locs = frame.f_locals del frame elif locs is None: locs = globs exec("""exec code in globs, locs""")
Example 26
Project: jawfish Author: war-and-code File: warnings.py License: MIT License | 5 votes |
def warn(message, category=None, stacklevel=1): """Issue a warning, or maybe ignore it or raise an exception.""" # Check if message is already a Warning object if isinstance(message, Warning): category = message.__class__ # Check category argument if category is None: category = UserWarning assert issubclass(category, Warning) # Get context information try: caller = sys._getframe(stacklevel) except ValueError: globals = sys.__dict__ lineno = 1 else: globals = caller.f_globals lineno = caller.f_lineno if '__name__' in globals: module = globals['__name__'] else: module = "<string>" filename = globals.get('__file__') if filename: fnl = filename.lower() if fnl.endswith((".pyc", ".pyo")): filename = filename[:-1] else: if module == "__main__": try: filename = sys.argv[0] except AttributeError: # embedded interpreters don't have sys.argv, see bug #839151 filename = '__main__' if not filename: filename = module registry = globals.setdefault("__warningregistry__", {}) warn_explicit(message, category, filename, lineno, module, registry, globals)
Example 27
Project: jawfish Author: war-and-code File: inspect.py License: MIT License | 5 votes |
def currentframe(): """Return the frame of the caller or None if this is not possible.""" return sys._getframe(1) if hasattr(sys, "_getframe") else None
Example 28
Project: jawfish Author: war-and-code File: inspect.py License: MIT License | 5 votes |
def stack(context=1): """Return a list of records for the stack above the caller's frame.""" return getouterframes(sys._getframe(1), context)
Example 29
Project: jawfish Author: war-and-code File: support.py License: MIT License | 5 votes |
def _filterwarnings(filters, quiet=False): """Catch the warnings, then check if all the expected warnings have been raised and re-raise unexpected warnings. If 'quiet' is True, only re-raise the unexpected warnings. """ # Clear the warning registry of the calling module # in order to re-raise the warnings. frame = sys._getframe(2) registry = frame.f_globals.get('__warningregistry__') if registry: registry.clear() with warnings.catch_warnings(record=True) as w: # Set filter "always" to record all warnings. Because # test_warnings swap the module, we need to look up in # the sys.modules dictionary. sys.modules['warnings'].simplefilter("always") yield WarningsRecorder(w) # Filter the recorded warnings reraise = list(w) missing = [] for msg, cat in filters: seen = False for w in reraise[:]: warning = w.message # Filter out the matching messages if (re.match(msg, str(warning), re.I) and issubclass(warning.__class__, cat)): seen = True reraise.remove(w) if not seen and not quiet: # This filter caught nothing missing.append((msg, cat.__name__)) if reraise: raise AssertionError("unhandled warning %s" % reraise[0]) if missing: raise AssertionError("filter (%r, %s) did not catch any warning" % missing[0])
Example 30
Project: pyscf Author: pyscf File: gw.py License: Apache License 2.0 | 5 votes |
def __LINE__(): return sys._getframe(1).f_lineno