Python sys._getframe() Examples

The following are code examples for showing how to use sys._getframe(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: tdx   Author: sqltxt   File: ExportEBK.py    (license) View Source Project 9 votes vote down vote up
def Menu():
    try:
        #??
        pdhk=win32gui.GetWindowRect(win32gui.FindWindowEx(win32gui.FindWindow('TdxW_MainFrame_Class','???????V7.35 - [???-?????]'),None,'#32770',None))
        win32api.SetCursorPos([pdhk[0]+330,pdhk[1]+10])
        time.sleep(1)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0)
        time.sleep(1)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0)
        time.sleep(1)
        #?????
        win32api.SetCursorPos([pdhk[0]+380,pdhk[1]+20+480])
        time.sleep(1)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0)
        time.sleep(1)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0)
        time.sleep(1)
    except Exception as e:
        ReadEBK.wx_msg(corp_id, secret,agentid,sys._getframe().f_code.co_name+'\t'+str(e))
        
#???????->????? 
Example 2
Project: tdx   Author: sqltxt   File: AutoRunTDX.py    (license) View Source Project 7 votes vote down vote up
def Free_quotation():
    time.sleep(3)
    try:
        Tab_handle = win32gui.FindWindowEx(win32gui.FindWindow('#32770','???????V7.35'),None,'SysTabControl32','Tab1')
        #print(hex(Tab_handle))
        #time.sleep(1)
        p=win32gui.GetWindowRect(Tab_handle)
        #print(p)
        #print(p[2])
        #print(p[3])
        win32api.SetCursorPos([p[0]+170,p[1]+7])
        time.sleep(1)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0,0,0)
        time.sleep(1)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0,0,0)
        time.sleep(1)
        win32gui.PostMessage(win32gui.FindWindowEx(win32gui.FindWindow('#32770','???????V7.35'),None,'Button','??'),win32con.BM_CLICK,0,0)
        time.sleep(3)
    except Exception as e:
        ReadEBK.wx_msg(corp_id, secret,agentid,sys._getframe().f_code.co_name+'\t'+str(e))

#????? 
Example 3
Project: tdx   Author: sqltxt   File: AutoRunTDX.py    (license) View Source Project 7 votes vote down vote up
def Stock_option(Index):
    try:
        #tjxg = win32gui.FindWindow('#32770','????')
        gs = win32gui.FindWindowEx(win32gui.FindWindow('#32770','????'),None,'ComboBox',None)
        #time.sleep(1)
        print(hex(gs))
        win32gui.SendMessage(gs,win32con.CB_SHOWDROPDOWN,1,0)  #??ComboBox???
        time.sleep(1)
        win32gui.SendMessage(gs,win32con.CB_SETCURSEL,Index,0)#???????
        time.sleep(1)
        win32gui.SendMessage(gs,win32con.WM_SETFOCUS,0,0)#????
        time.sleep(1)
        win32gui.SendMessage(gs,win32con.WM_KEYDOWN,0,0)#???????
        time.sleep(1)
        win32gui.SendMessage(gs,win32con.WM_KEYUP,0,0) 
        time.sleep(1)
    except Exception as e:
        ReadEBK.wx_msg(corp_id, secret,agentid,sys._getframe().f_code.co_name+'\t'+str(e))
#???? 
Example 4
Project: Dockerfiles   Author: appscode   File: pydotenv.py    (license) View Source Project 6 votes vote down vote up
def find_dotenv(filename='.env', raise_error_if_not_found=False, usecwd=False):
    """
    Search in increasingly higher folders for the given file

    Returns path to the file if found, or an empty string otherwise
    """
    if usecwd or '__file__' not in globals():
        # should work without __file__, e.g. in REPL or IPython notebook
        path = os.getcwd()
    else:
        # will work for .py files
        frame_filename = sys._getframe().f_back.f_code.co_filename
        path = os.path.dirname(os.path.abspath(frame_filename))

    for dirname in _walk_to_root(path):
        check_path = os.path.join(dirname, filename)
        if os.path.exists(check_path):
            return check_path

    if raise_error_if_not_found:
        raise IOError('File not found')

    return '' 
Example 5
Project: libbuild   Author: appscode   File: pydotenv.py    (license) View Source Project 6 votes vote down vote up
def find_dotenv(filename='.env', raise_error_if_not_found=False, usecwd=False):
    """
    Search in increasingly higher folders for the given file

    Returns path to the file if found, or an empty string otherwise
    """
    if usecwd or '__file__' not in globals():
        # should work without __file__, e.g. in REPL or IPython notebook
        path = os.getcwd()
    else:
        # will work for .py files
        frame_filename = sys._getframe().f_back.f_code.co_filename
        path = os.path.dirname(os.path.abspath(frame_filename))

    for dirname in _walk_to_root(path):
        check_path = os.path.join(dirname, filename)
        if os.path.exists(check_path):
            return check_path

    if raise_error_if_not_found:
        raise IOError('File not found')

    return '' 
Example 6
Project: debugger-utils   Author: spacewander   File: gdb_utils.py    (MIT License) View Source Project 6 votes vote down vote up
def eval_template(template, cmd):
    cmdname = cmd.__name__
    classname = to_classname(cmd.__name__)
    # Use the same technic as namedtuple
    class_definition = template.format(
        cmdname = cmdname,
        docstring = cmd.__doc__ if cmd.__doc__ is not None else '',
        classname = classname
    )
    namespace = dict(__name__='template_%s' % cmdname)
    exec(class_definition, namespace)
    result = namespace[classname]
    result.cmd = cmd
    result._source = class_definition
    try:
        result.__module__ = sys._getframe(1).f_globals.get(
            '__name__', '__main__')
    except (AttributeError, ValueError):
        pass
    return result 
Example 7
Project: kinect-2-libras   Author: inessadl   File: bdb.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def set_continue(self):
        # Don't stop except at breakpoints or when finished
        self._set_stopinfo(self.botframe, None, -1)
        if not self.breaks:
            # no breakpoints; run without debugger overhead
            sys.settrace(None)
            frame = sys._getframe().f_back
            while frame and frame is not self.botframe:
                del frame.f_trace
                frame = frame.f_back 
Example 8
Project: SoCFoundationFlow   Author: mattaw   File: color_gcc.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def format(self, rec):
		frame = sys._getframe()
		while frame:
			func = frame.f_code.co_name
			if func == 'exec_command':
				cmd = frame.f_locals['cmd']
				if isinstance(cmd, list) and ('gcc' in cmd[0] or 'g++' in cmd[0]):
					lines = []
					for line in rec.msg.splitlines():
						if 'warning: ' in line:
							lines.append(self.colors.YELLOW + line)
						elif 'error: ' in line:
							lines.append(self.colors.RED + line)
						elif 'note: ' in line:
							lines.append(self.colors.CYAN + line)
						else:
							lines.append(line)
					rec.msg = "\n".join(lines)
			frame = frame.f_back
		return Logs.formatter.format(self, rec) 
Example 9
Project: SoCFoundationFlow   Author: mattaw   File: color_rvct.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def format(self, rec):
		frame = sys._getframe()
		while frame:
			func = frame.f_code.co_name
			if func == 'exec_command':
				cmd = frame.f_locals['cmd']
				if isinstance(cmd, list) and ('armcc' in cmd[0] or 'armld' in cmd[0]):
					lines = []
					for line in rec.msg.splitlines():
						if 'Warning: ' in line:
							lines.append(self.colors.YELLOW + line)
						elif 'Error: ' in line:
							lines.append(self.colors.RED + line)
							errors.append(line)
						elif 'note: ' in line:
							lines.append(self.colors.CYAN + line)
						else:
							lines.append(line)
					rec.msg = "\n".join(lines)
			frame = frame.f_back
		return Logs.formatter.format(self, rec) 
Example 10
Project: SoCFoundationFlow   Author: mattaw   File: color_gcc.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def format(self, rec):
		frame = sys._getframe()
		while frame:
			func = frame.f_code.co_name
			if func == 'exec_command':
				cmd = frame.f_locals['cmd']
				if isinstance(cmd, list) and ('gcc' in cmd[0] or 'g++' in cmd[0]):
					lines = []
					for line in rec.msg.splitlines():
						if 'warning: ' in line:
							lines.append(self.colors.YELLOW + line)
						elif 'error: ' in line:
							lines.append(self.colors.RED + line)
						elif 'note: ' in line:
							lines.append(self.colors.CYAN + line)
						else:
							lines.append(line)
					rec.msg = "\n".join(lines)
			frame = frame.f_back
		return Logs.formatter.format(self, rec) 
Example 11
Project: SoCFoundationFlow   Author: mattaw   File: color_rvct.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def format(self, rec):
		frame = sys._getframe()
		while frame:
			func = frame.f_code.co_name
			if func == 'exec_command':
				cmd = frame.f_locals['cmd']
				if isinstance(cmd, list) and ('armcc' in cmd[0] or 'armld' in cmd[0]):
					lines = []
					for line in rec.msg.splitlines():
						if 'Warning: ' in line:
							lines.append(self.colors.YELLOW + line)
						elif 'Error: ' in line:
							lines.append(self.colors.RED + line)
							errors.append(line)
						elif 'note: ' in line:
							lines.append(self.colors.CYAN + line)
						else:
							lines.append(line)
					rec.msg = "\n".join(lines)
			frame = frame.f_back
		return Logs.formatter.format(self, rec) 
Example 12
Project: SoCFoundationFlow   Author: mattaw   File: color_gcc.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def format(self, rec):
		frame = sys._getframe()
		while frame:
			func = frame.f_code.co_name
			if func == 'exec_command':
				cmd = frame.f_locals['cmd']
				if isinstance(cmd, list) and ('gcc' in cmd[0] or 'g++' in cmd[0]):
					lines = []
					for line in rec.msg.splitlines():
						if 'warning: ' in line:
							lines.append(self.colors.YELLOW + line)
						elif 'error: ' in line:
							lines.append(self.colors.RED + line)
						elif 'note: ' in line:
							lines.append(self.colors.CYAN + line)
						else:
							lines.append(line)
					rec.msg = "\n".join(lines)
			frame = frame.f_back
		return Logs.formatter.format(self, rec) 
Example 13
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: web.py    (MIT License) View Source Project 6 votes vote down vote up
def render_string(self, template_name, **kwargs):
        """Generate the given template with the given arguments.

        We return the generated byte string (in utf8). To generate and
        write a template as a response, use render() above.
        """
        # 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 14
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: web.py    (MIT License) View Source Project 6 votes vote down vote up
def render_string(self, template_name, **kwargs):
        """Generate the given template with the given arguments.

        We return the generated byte string (in utf8). To generate and
        write a template as a response, use render() above.
        """
        # 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: noc-orchestrator   Author: DirceuSilvaLabs   File: web.py    (MIT License) View Source Project 6 votes vote down vote up
def render_string(self, template_name, **kwargs):
        """Generate the given template with the given arguments.

        We return the generated byte string (in utf8). To generate and
        write a template as a response, use render() above.
        """
        # 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: veneer-py   Author: flowmatters   File: extensions.py    (license) View Source Project 6 votes vote down vote up
def add_network_methods(target):
    '''
    Attach extension methods to an object that represents a Veneer network.
    Note: The 'network_' prefix will be removed from method names.

    target: Veneer network object to attach extension methods to.
    '''
    import veneer.extensions as extensions # Import self to inspect available functions

    # Generate dict of {function name: function}, skipping this function
    this_func_name = sys._getframe().f_code.co_name
    funcs = inspect.getmembers(extensions, inspect.isfunction)
    funcs = dict((func_name, func) for func_name, func in funcs
                  if func_name != this_func_name
            )

    # Assign functions to target, removing the 'network_' prefix
    for f_name, f in funcs.items():
        if f_name.startswith('network_'):
            f_name = f_name.replace('network_', '')
        setattr(target, f_name, MethodType(f, target)) 
Example 17
Project: catalearn   Author: Catalearn   File: local_params.py    (license) View Source Project 6 votes vote down vote up
def get_local_vars(source, namespace):

    # local_vars = sys._getframe(depth).f_locals

    local_vars_names = set(namespace.keys())

    root = ast.parse(source)

    required_vars_names = set()
    for node in ast.walk(root):
        if isinstance(node, ast.Name):
            required_vars_names.add(node.id)

    builtin_vars_names = set(vars(builtins).keys())

    required_local_vars = required_vars_names & local_vars_names

    # we might want to add a compiler-ish thing in the future 

    params = {}
    for v in required_local_vars:
        params[v] = namespace[v]

    return params 
Example 18
Project: catalearn   Author: Catalearn   File: runner.py    (license) View Source Project 6 votes vote down vote up
def search(func, depth=1):
    local_vars = sys._getframe(depth).f_locals
    source = get_source_code(func)
    tree = ast.parse(source)
    child_funcs = []
    for node in ast.walk(tree):
        if isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name):
                child_funcs.append(node.func.id)
        elif (isinstance(node, ast.Name) and node.id in local_vars and callable(local_vars[node.id]) and node.id not in sys.builtin_module_names):
            child_funcs.append(node.id)

    child_load_str = ''
    for child in child_funcs:
        if child in local_vars:
            try:
                load_string = search(local_vars[child], depth=(depth + 1))
                child_load_str += load_string + '\n'
            except Exception as e:
                pass
            
    load_str = child_load_str + source
    return load_str 
Example 19
Project: tdx   Author: sqltxt   File: ExportEBK.py    (license) View Source Project 6 votes vote down vote up
def Save():
    try:
        win32gui.PostMessage(win32gui.FindWindowEx(win32gui.FindWindow('#32770','???'),None,'Button','??(&S)'),win32con.BM_CLICK,0,0)
        time.sleep(1)
        global handle
        handle = None
        win32gui.EnumChildWindows(win32gui.FindWindow('#32770','?????'),handle_window,'?(&Y)')
        if handle!= None:
            win32gui.PostMessage(handle,win32con.BM_CLICK,0,0)
        time.sleep(3)
    except Exception as e:
        ReadEBK.wx_msg(corp_id, secret,agentid,sys._getframe().f_code.co_name+'\t'+str(e)) 
Example 20
Project: hostapd-mana   Author: adde88   File: warning.py    (license) View Source Project 6 votes vote down vote up
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 21
Project: charm-plumgrid-gateway   Author: openstack   File: debug.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def set_trace(addr=DEFAULT_ADDR, port=DEFAULT_PORT):
    """
    Set a trace point using the remote debugger
    """
    atexit.register(close_port, port)
    try:
        log("Starting a remote python debugger session on %s:%s" % (addr,
                                                                    port))
        open_port(port)
        debugger = Rpdb(addr=addr, port=port)
        debugger.set_trace(sys._getframe().f_back)
    except:
        _error("Cannot start a remote debug session on %s:%s" % (addr,
                                                                 port)) 
Example 22
Project: python-   Author: secondtonone1   File: six.py    (license) View Source Project 5 votes vote down vote up
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 23
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def run_script(dist_spec, script_name):
    """Locate distribution `dist_spec` and run its `script_name` script"""
    ns = sys._getframe(1).f_globals
    name = ns['__name__']
    ns.clear()
    ns['__name__'] = name
    require(dist_spec)[0].run_script(script_name, ns)


# backward compatibility 
Example 24
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def run_script(self, requires, script_name):
        """Locate distribution for `requires` and run `script_name` script"""
        ns = sys._getframe(1).f_globals
        name = ns['__name__']
        ns.clear()
        ns['__name__'] = name
        self.require(requires)[0].run_script(script_name, ns) 
Example 25
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def issue_warning(*args, **kw):
    level = 1
    g = globals()
    try:
        # find the first stack frame that is *not* code in
        # the pkg_resources module, to use for the warning
        while sys._getframe(level).f_globals is g:
            level += 1
    except ValueError:
        pass
    warnings.warn(stacklevel=level + 1, *args, **kw) 
Example 26
Project: python-   Author: secondtonone1   File: six.py    (license) View Source Project 5 votes vote down vote up
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 27
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def run_script(dist_spec, script_name):
    """Locate distribution `dist_spec` and run its `script_name` script"""
    ns = sys._getframe(1).f_globals
    name = ns['__name__']
    ns.clear()
    ns['__name__'] = name
    require(dist_spec)[0].run_script(script_name, ns)


# backward compatibility 
Example 28
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def run_script(self, requires, script_name):
        """Locate distribution for `requires` and run `script_name` script"""
        ns = sys._getframe(1).f_globals
        name = ns['__name__']
        ns.clear()
        ns['__name__'] = name
        self.require(requires)[0].run_script(script_name, ns) 
Example 29
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def issue_warning(*args, **kw):
    level = 1
    g = globals()
    try:
        # find the first stack frame that is *not* code in
        # the pkg_resources module, to use for the warning
        while sys._getframe(level).f_globals is g:
            level += 1
    except ValueError:
        pass
    warnings.warn(stacklevel=level + 1, *args, **kw) 
Example 30
Project: environ_config   Author: hynek   File: secrets.py    (MIT License) View Source Project 5 votes vote down vote up
def __repr__(self):
        f = sys._getframe(2)

        if f.f_code.co_name == "repr_":
            return "<SECRET>"
        else:
            return str.__repr__(self) 
Example 31
Project: my-first-blog   Author: AnkurBegining   File: six.py    (license) View Source Project 5 votes vote down vote up
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 32
Project: my-first-blog   Author: AnkurBegining   File: six.py    (license) View Source Project 5 votes vote down vote up
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 33
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def run_script(dist_spec, script_name):
    """Locate distribution `dist_spec` and run its `script_name` script"""
    ns = sys._getframe(1).f_globals
    name = ns['__name__']
    ns.clear()
    ns['__name__'] = name
    require(dist_spec)[0].run_script(script_name, ns)


# backward compatibility 
Example 34
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def run_script(self, requires, script_name):
        """Locate distribution for `requires` and run `script_name` script"""
        ns = sys._getframe(1).f_globals
        name = ns['__name__']
        ns.clear()
        ns['__name__'] = name
        self.require(requires)[0].run_script(script_name, ns) 
Example 35
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def issue_warning(*args, **kw):
    level = 1
    g = globals()
    try:
        # find the first stack frame that is *not* code in
        # the pkg_resources module, to use for the warning
        while sys._getframe(level).f_globals is g:
            level += 1
    except ValueError:
        pass
    warnings.warn(stacklevel=level + 1, *args, **kw) 
Example 36
Project: my-first-blog   Author: AnkurBegining   File: six.py    (license) View Source Project 5 votes vote down vote up
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 37
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def run_script(dist_spec, script_name):
    """Locate distribution `dist_spec` and run its `script_name` script"""
    ns = sys._getframe(1).f_globals
    name = ns['__name__']
    ns.clear()
    ns['__name__'] = name
    require(dist_spec)[0].run_script(script_name, ns)


# backward compatibility 
Example 38
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def run_script(self, requires, script_name):
        """Locate distribution for `requires` and run `script_name` script"""
        ns = sys._getframe(1).f_globals
        name = ns['__name__']
        ns.clear()
        ns['__name__'] = name
        self.require(requires)[0].run_script(script_name, ns) 
Example 39
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def issue_warning(*args, **kw):
    level = 1
    g = globals()
    try:
        # find the first stack frame that is *not* code in
        # the pkg_resources module, to use for the warning
        while sys._getframe(level).f_globals is g:
            level += 1
    except ValueError:
        pass
    warnings.warn(stacklevel=level + 1, *args, **kw) 
Example 40
Project: charm-swift-proxy   Author: openstack   File: debug.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def set_trace(addr=DEFAULT_ADDR, port=DEFAULT_PORT):
    """
    Set a trace point using the remote debugger
    """
    atexit.register(close_port, port)
    try:
        log("Starting a remote python debugger session on %s:%s" % (addr,
                                                                    port))
        open_port(port)
        debugger = Rpdb(addr=addr, port=port)
        debugger.set_trace(sys._getframe().f_back)
    except Exception:
        _error("Cannot start a remote debug session on %s:%s" % (addr,
                                                                 port)) 
Example 41
Project: jobs   Author: josiahcarlson   File: jobs.py    (license) View Source Project 5 votes vote down vote up
def _get_caller():
    return sys._getframe(2).f_code 
Example 42
Project: kinect-2-libras   Author: inessadl   File: pdb.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def set_trace():
    Pdb().set_trace(sys._getframe().f_back)

# Post-Mortem interface 
Example 43
Project: kinect-2-libras   Author: inessadl   File: warnings.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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 44
Project: kinect-2-libras   Author: inessadl   File: bdb.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def set_trace(self, frame=None):
        """Start debugging from `frame`.

        If frame is not specified, debugging starts from caller's frame.
        """
        if frame is None:
            frame = sys._getframe().f_back
        self.reset()
        while frame:
            frame.f_trace = self.trace_dispatch
            self.botframe = frame
            frame = frame.f_back
        self.set_step()
        sys.settrace(self.trace_dispatch) 
Example 45
Project: kinect-2-libras   Author: inessadl   File: inspect.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def stack(context=1):
    """Return a list of records for the stack above the caller's frame."""
    return getouterframes(sys._getframe(1), context) 
Example 46
Project: kinect-2-libras   Author: inessadl   File: doctest.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def set_trace(self, frame=None):
        self.__debugger_used = True
        if frame is None:
            frame = sys._getframe().f_back
        pdb.Pdb.set_trace(self, frame) 
Example 47
Project: whatstyle   Author: mikr   File: whatstyle.py    (MIT License) View Source Project 5 votes vote down vote up
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 48
Project: googletranslate.popclipext   Author: wizyoung   File: six.py    (MIT License) View Source Project 5 votes vote down vote up
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 49
Project: otRebuilder   Author: Pal3love   File: testSupport.py    (MIT License) View Source Project 5 votes vote down vote up
def _gatherTestCasesFromCallerByMagic():
	# UGLY magic: fetch TestClass subclasses from the globals of our
	# caller's caller.
	frame = sys._getframe(2)
	return _gatherTestCasesFromDict(frame.f_globals) 
Example 50
Project: oscars2016   Author: 0x0ece   File: six.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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_""")