Python __builtin__.__dict__() Examples

The following are 30 code examples of __builtin__.__dict__(). 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 also want to check out all available functions/classes of the module __builtin__ , or try the search function .
Example #1
Source File: backdoor.py    From satori with Apache License 2.0 8 votes vote down vote up
def _create_interactive_locals(self):
        # Create and return a *new* locals dictionary based on self.locals,
        # and set any new entries in it. (InteractiveConsole does not
        # copy its locals value)
        _locals = self.locals.copy()
        # __builtins__ may either be the __builtin__ module or
        # __builtin__.__dict__; in the latter case typing
        # locals() at the backdoor prompt spews out lots of
        # useless stuff
        try:
            import __builtin__
            _locals["__builtins__"] = __builtin__
        except ImportError:
            import builtins
            _locals["builtins"] = builtins
            _locals['__builtins__'] = builtins
        return _locals 
Example #2
Source File: rlcompleter.py    From meddle with MIT License 7 votes vote down vote up
def complete(self, text, state):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """
        if self.use_main_ns:
            self.namespace = __main__.__dict__

        if state == 0:
            if "." in text:
                self.matches = self.attr_matches(text)
            else:
                self.matches = self.global_matches(text)
        try:
            return self.matches[state]
        except IndexError:
            return None 
Example #3
Source File: rlcompleter.py    From meddle with MIT License 7 votes vote down vote up
def global_matches(self, text):
        """Compute matches when text is a simple name.

        Return a list of all keywords, built-in functions and names currently
        defined in self.namespace that match.

        """
        import keyword
        matches = []
        n = len(text)
        for word in keyword.kwlist:
            if word[:n] == text:
                matches.append(word)
        for nspace in [__builtin__.__dict__, self.namespace]:
            for word, val in nspace.items():
                if word[:n] == text and word != "__builtins__":
                    matches.append(self._callable_postfix(val, word))
        return matches 
Example #4
Source File: test_regrtest.py    From ironpython2 with Apache License 2.0 7 votes vote down vote up
def test_forever(self):
        # test --forever
        code = textwrap.dedent("""
            import __builtin__
            import unittest
            from test import support

            class ForeverTester(unittest.TestCase):
                def test_run(self):
                    # Store the state in the __builtin__ module, because the test
                    # module is reload at each run
                    if 'RUN' in __builtin__.__dict__:
                        __builtin__.__dict__['RUN'] += 1
                        if __builtin__.__dict__['RUN'] >= 3:
                            self.fail("fail at the 3rd runs")
                    else:
                        __builtin__.__dict__['RUN'] = 1

            def test_main():
                support.run_unittest(ForeverTester)
        """)
        test = self.create_test('forever', code=code)
        output = self.run_tests('--forever', test, exitcode=2)
        self.check_executed_tests(output, [test]*3, failed=test) 
Example #5
Source File: rlcompleter.py    From ironpython2 with Apache License 2.0 7 votes vote down vote up
def complete(self, text, state):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """
        if self.use_main_ns:
            self.namespace = __main__.__dict__

        if state == 0:
            if "." in text:
                self.matches = self.attr_matches(text)
            else:
                self.matches = self.global_matches(text)
        try:
            return self.matches[state]
        except IndexError:
            return None 
Example #6
Source File: bytecodecompiler.py    From Computable with MIT License 6 votes vote down vote up
def global_info(self,var_num):
        # This is the name value is known by
        var_name = self.codeobject.co_names[var_num]

        # First, figure out who owns this global
        myHash = id(self.function.func_globals)
        for module_name in sys.modules:
            module = sys.modules[module_name]
            if module and id(module.__dict__) == myHash:
                break
        else:
            raise ValueError('Cannot locate module owning %s' % var_name)
        return module_name,var_name

    ##################################################################
    #                         MEMBER CODEUP                          #
    ################################################################## 
Example #7
Source File: pydevd_traceproperty.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def replace_builtin_property(new_property=None):
    if new_property is None:
        new_property = DebugProperty
    original = property
    if IS_PY2:
        try:
            import __builtin__
            __builtin__.__dict__['property'] = new_property
        except:
            pydev_log.exception()  # @Reimport
    else:
        try:
            import builtins  # Python 3.0 does not have the __builtin__ module @UnresolvedImport
            builtins.__dict__['property'] = new_property
        except:
            pydev_log.exception()  # @Reimport
    return original


#=======================================================================================================================
# DebugProperty
#======================================================================================================================= 
Example #8
Source File: rlcompleter.py    From BinderFilter with MIT License 6 votes vote down vote up
def global_matches(self, text):
        """Compute matches when text is a simple name.

        Return a list of all keywords, built-in functions and names currently
        defined in self.namespace that match.

        """
        import keyword
        matches = []
        n = len(text)
        for word in keyword.kwlist:
            if word[:n] == text:
                matches.append(word)
        for nspace in [__builtin__.__dict__, self.namespace]:
            for word, val in nspace.items():
                if word[:n] == text and word != "__builtins__":
                    matches.append(self._callable_postfix(val, word))
        return matches 
Example #9
Source File: rlcompleter.py    From BinderFilter with MIT License 6 votes vote down vote up
def complete(self, text, state):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """
        if self.use_main_ns:
            self.namespace = __main__.__dict__

        if state == 0:
            if "." in text:
                self.matches = self.attr_matches(text)
            else:
                self.matches = self.global_matches(text)
        try:
            return self.matches[state]
        except IndexError:
            return None 
Example #10
Source File: _pydev_completer.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def complete(self, text):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """
        if self.use_main_ns:
            # In pydev this option should never be used
            raise RuntimeError('Namespace must be provided!')
            self.namespace = __main__.__dict__  # @UndefinedVariable

        if "." in text:
            return self.attr_matches(text)
        else:
            return self.global_matches(text) 
Example #11
Source File: _pydev_completer.py    From PyDev.Debugger with Eclipse Public License 1.0 6 votes vote down vote up
def global_matches(self, text):
        """Compute matches when text is a simple name.

        Return a list of all keywords, built-in functions and names currently
        defined in self.namespace or self.global_namespace that match.

        """

        def get_item(obj, attr):
            return obj[attr]

        a = {}

        for dict_with_comps in [__builtin__.__dict__, self.namespace, self.global_namespace]:  # @UndefinedVariable
            a.update(dict_with_comps)

        filter = _StartsWithFilter(text)

        return dir2(a, a.keys(), get_item, filter) 
Example #12
Source File: rlcompleter.py    From oss-ftp with MIT License 6 votes vote down vote up
def global_matches(self, text):
        """Compute matches when text is a simple name.

        Return a list of all keywords, built-in functions and names currently
        defined in self.namespace that match.

        """
        import keyword
        matches = []
        n = len(text)
        for word in keyword.kwlist:
            if word[:n] == text:
                matches.append(word)
        for nspace in [__builtin__.__dict__, self.namespace]:
            for word, val in nspace.items():
                if word[:n] == text and word != "__builtins__":
                    matches.append(self._callable_postfix(val, word))
        return matches 
Example #13
Source File: start.py    From RAFCON with Eclipse Public License 1.0 6 votes vote down vote up
def setup_environment():
    """Ensures that the environmental variable RAFCON_LIB_PATH is existent
    """
    # The RAFCON_LIB_PATH points to a path with common RAFCON libraries
    # If the env variable is not set, we have to determine it.
    if not os.environ.get('RAFCON_LIB_PATH', None):
        rafcon_library_path = resources.get_data_file_path("rafcon", "libraries")
        if rafcon_library_path:
            os.environ['RAFCON_LIB_PATH'] = rafcon_library_path
        else:
            logger.warning("Could not find root directory of RAFCON libraries. Please specify manually using the "
                           "env var RAFCON_LIB_PATH")

    # Install dummy _ builtin function in case i18.setup_l10n() is not called
    if sys.version_info >= (3,):
        import builtins as builtins23
    else:
        import __builtin__ as builtins23
    if "_" not in builtins23.__dict__:
        builtins23.__dict__["_"] = lambda s: s 
Example #14
Source File: rlcompleter.py    From oss-ftp with MIT License 6 votes vote down vote up
def complete(self, text, state):
        """Return the next possible completion for 'text'.

        This is called successively with state == 0, 1, 2, ... until it
        returns None.  The completion should begin with 'text'.

        """
        if self.use_main_ns:
            self.namespace = __main__.__dict__

        if state == 0:
            if "." in text:
                self.matches = self.attr_matches(text)
            else:
                self.matches = self.global_matches(text)
        try:
            return self.matches[state]
        except IndexError:
            return None 
Example #15
Source File: interactiveshell.py    From Computable with MIT License 6 votes vote down vote up
def init_builtins(self):
        # A single, static flag that we set to True.  Its presence indicates
        # that an IPython shell has been created, and we make no attempts at
        # removing on exit or representing the existence of more than one
        # IPython at a time.
        builtin_mod.__dict__['__IPYTHON__'] = True

        # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
        # manage on enter/exit, but with all our shells it's virtually
        # impossible to get all the cases right.  We're leaving the name in for
        # those who adapted their codes to check for this flag, but will
        # eventually remove it after a few more releases.
        builtin_mod.__dict__['__IPYTHON__active'] = \
                                          'Deprecated, check for __IPYTHON__'

        self.builtin_trap = BuiltinTrap(shell=self) 
Example #16
Source File: run.py    From bootstrap.pytorch with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def activate_profiler():
    if sys.version_info[0] == 3:  # PY3
        import builtins
    else:
        import __builtin__ as builtins
    if Options()['misc'].get('profile', False):
        # if profiler is activated, associate line_profiler
        Logger()('Activating line_profiler...')
        try:
            import line_profiler
        except ModuleNotFoundError:
            Logger()('Failed to import line_profiler.', log_level=Logger.ERROR, raise_error=False)
            Logger()('Please install it from https://github.com/rkern/line_profiler', log_level=Logger.ERROR, raise_error=False)
            return
        prof = line_profiler.LineProfiler()
        builtins.__dict__['profile'] = prof
    else:
        # otherwise, create a blank profiler, to disable profiling code
        builtins.__dict__['profile'] = lambda func: func
        prof = None
    return prof 
Example #17
Source File: rlcompleter.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def global_matches(self, text):
        """Compute matches when text is a simple name.

        Return a list of all keywords, built-in functions and names currently
        defined in self.namespace that match.

        """
        import keyword
        matches = []
        seen = {"__builtins__"}
        n = len(text)
        for word in keyword.kwlist:
            if word[:n] == text:
                seen.add(word)
                matches.append(word)
        for nspace in [self.namespace, __builtin__.__dict__]:
            for word, val in nspace.items():
                if word[:n] == text and word not in seen:
                    seen.add(word)
                    matches.append(self._callable_postfix(val, word))
        return matches 
Example #18
Source File: interactiveshell.py    From Computable with MIT License 6 votes vote down vote up
def init_sys_modules(self):
        # We need to insert into sys.modules something that looks like a
        # module but which accesses the IPython namespace, for shelve and
        # pickle to work interactively. Normally they rely on getting
        # everything out of __main__, but for embedding purposes each IPython
        # instance has its own private namespace, so we can't go shoving
        # everything into __main__.

        # note, however, that we should only do this for non-embedded
        # ipythons, which really mimic the __main__.__dict__ with their own
        # namespace.  Embedded instances, on the other hand, should not do
        # this because they need to manage the user local/global namespaces
        # only, but they live within a 'normal' __main__ (meaning, they
        # shouldn't overtake the execution environment of the script they're
        # embedded in).

        # This is overridden in the InteractiveShellEmbed subclass to a no-op.
        main_name = self.user_module.__name__
        sys.modules[main_name] = self.user_module 
Example #19
Source File: gateway.py    From execnet with MIT License 6 votes vote down vote up
def _find_non_builtin_globals(source, codeobj):
    import ast

    try:
        import __builtin__
    except ImportError:
        import builtins as __builtin__

    vars = dict.fromkeys(codeobj.co_varnames)
    return [
        node.id
        for node in ast.walk(ast.parse(source))
        if isinstance(node, ast.Name)
        and node.id not in vars
        and node.id not in __builtin__.__dict__
    ] 
Example #20
Source File: main.py    From CVE-2016-6366 with MIT License 5 votes vote down vote up
def update_session(fname=None):
    if fname is None:
        fname = conf.session
    try:
        s = cPickle.load(gzip.open(fname,"rb"))
    except IOError:
        s = cPickle.load(open(fname,"rb"))
    scapy_session = __builtin__.__dict__["scapy_session"]
    scapy_session.update(s)


################
##### Main #####
################ 
Example #21
Source File: main.py    From mptcp-abuse with GNU General Public License v2.0 5 votes vote down vote up
def save_session(fname=None, session=None, pickleProto=-1):
    if fname is None:
        fname = conf.session
        if not fname:
            conf.session = fname = utils.get_temp_file(keep=True)
            log_interactive.info("Use [%s] as session file" % fname)
    if session is None:
        session = __builtin__.__dict__["scapy_session"]

    to_be_saved = session.copy()
        
    if to_be_saved.has_key("__builtins__"):
        del(to_be_saved["__builtins__"])

    for k in to_be_saved.keys():
        if type(to_be_saved[k]) in [types.TypeType, types.ClassType, types.ModuleType]:
             log_interactive.error("[%s] (%s) can't be saved." % (k, type(to_be_saved[k])))
             del(to_be_saved[k])

    try:
        os.rename(fname, fname+".bak")
    except OSError:
        pass
    f=gzip.open(fname,"wb")
    cPickle.dump(to_be_saved, f, pickleProto)
    f.close() 
Example #22
Source File: memory_profiler.py    From pyFileFixity with MIT License 5 votes vote down vote up
def __call__(self, func):
        if not hasattr(func, "__call__"):
            raise ValueError("Value must be callable")

        self.add_function(func)
        f = self.wrap_function(func)
        f.__module__ = func.__module__
        f.__name__ = func.__name__
        f.__doc__ = func.__doc__
        f.__dict__.update(getattr(func, '__dict__', {}))
        return f 
Example #23
Source File: autorun.py    From CVE-2016-6366 with MIT License 5 votes vote down vote up
def autorun_commands(cmds,my_globals=None,verb=0):
    sv = conf.verb
    import __builtin__
    try:
        try:
            if my_globals is None:
                my_globals = __import__("scapy.all").all.__dict__
            conf.verb = verb
            interp = ScapyAutorunInterpreter(my_globals)
            cmd = ""
            cmds = cmds.splitlines()
            cmds.append("") # ensure we finish multiline commands
            cmds.reverse()
            __builtin__.__dict__["_"] = None
            while 1:
                if cmd:
                    sys.stderr.write(sys.__dict__.get("ps2","... "))
                else:
                    sys.stderr.write(str(sys.__dict__.get("ps1",ColorPrompt())))
                    
                l = cmds.pop()
                print l
                cmd += "\n"+l
                if interp.runsource(cmd):
                    continue
                if interp.error:
                    return 0
                cmd = ""
                if len(cmds) <= 1:
                    break
        except SystemExit:
            pass
    finally:
        conf.verb = sv
    return _ 
Example #24
Source File: main.py    From CVE-2016-6366 with MIT License 5 votes vote down vote up
def save_session(fname=None, session=None, pickleProto=-1):
    if fname is None:
        fname = conf.session
        if not fname:
            conf.session = fname = utils.get_temp_file(keep=True)
            log_interactive.info("Use [%s] as session file" % fname)
    if session is None:
        session = __builtin__.__dict__["scapy_session"]

    to_be_saved = session.copy()
        
    if to_be_saved.has_key("__builtins__"):
        del(to_be_saved["__builtins__"])

    for k in to_be_saved.keys():
        if type(to_be_saved[k]) in [types.TypeType, types.ClassType, types.ModuleType]:
             log_interactive.error("[%s] (%s) can't be saved." % (k, type(to_be_saved[k])))
             del(to_be_saved[k])

    try:
        os.rename(fname, fname+".bak")
    except OSError:
        pass
    f=gzip.open(fname,"wb")
    cPickle.dump(to_be_saved, f, pickleProto)
    f.close() 
Example #25
Source File: main.py    From CVE-2016-6366 with MIT License 5 votes vote down vote up
def _load(module):
    try:
        mod = __import__(module,globals(),locals(),".")
        __builtin__.__dict__.update(mod.__dict__)
    except Exception,e:
        log_interactive.error(e) 
Example #26
Source File: autorun.py    From smod-1 with GNU General Public License v2.0 5 votes vote down vote up
def autorun_commands(cmds,my_globals=None,verb=0):
    sv = conf.verb
    import __builtin__
    try:
        try:
            if my_globals is None:
                my_globals = __import__("scapy.all").all.__dict__
            conf.verb = verb
            interp = ScapyAutorunInterpreter(my_globals)
            cmd = ""
            cmds = cmds.splitlines()
            cmds.append("") # ensure we finish multiline commands
            cmds.reverse()
            __builtin__.__dict__["_"] = None
            while 1:
                if cmd:
                    sys.stderr.write(sys.__dict__.get("ps2","... "))
                else:
                    sys.stderr.write(str(sys.__dict__.get("ps1",ColorPrompt())))
                    
                l = cmds.pop()
                print l
                cmd += "\n"+l
                if interp.runsource(cmd):
                    continue
                if interp.error:
                    return 0
                cmd = ""
                if len(cmds) <= 1:
                    break
        except SystemExit:
            pass
    finally:
        conf.verb = sv
    return _ 
Example #27
Source File: main.py    From CVE-2016-6366 with MIT License 5 votes vote down vote up
def load_session(fname=None):
    if fname is None:
        fname = conf.session
    try:
        s = cPickle.load(gzip.open(fname,"rb"))
    except IOError:
        s = cPickle.load(open(fname,"rb"))
    scapy_session = __builtin__.__dict__["scapy_session"]
    scapy_session.clear()
    scapy_session.update(s) 
Example #28
Source File: main.py    From mptcp-abuse with GNU General Public License v2.0 5 votes vote down vote up
def _load(module):
    try:
        mod = __import__(module,globals(),locals(),".")
        __builtin__.__dict__.update(mod.__dict__)
    except Exception,e:
        log_interactive.error(e) 
Example #29
Source File: main.py    From mptcp-abuse with GNU General Public License v2.0 5 votes vote down vote up
def update_session(fname=None):
    if fname is None:
        fname = conf.session
    try:
        s = cPickle.load(gzip.open(fname,"rb"))
    except IOError:
        s = cPickle.load(open(fname,"rb"))
    scapy_session = __builtin__.__dict__["scapy_session"]
    scapy_session.update(s)


################
##### Main #####
################ 
Example #30
Source File: main.py    From mptcp-abuse with GNU General Public License v2.0 5 votes vote down vote up
def load_session(fname=None):
    if fname is None:
        fname = conf.session
    try:
        s = cPickle.load(gzip.open(fname,"rb"))
    except IOError:
        s = cPickle.load(open(fname,"rb"))
    scapy_session = __builtin__.__dict__["scapy_session"]
    scapy_session.clear()
    scapy_session.update(s)