Python builtins 模块,__dict__() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用builtins.__dict__()

项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def __init__(self, f_code, f_closure, f_globals, f_locals):
        self.f_code = f_code
        self.f_globals = f_globals
        self.f_locals = f_locals

        self.f_builtins = f_globals.get('__builtins__')
        if isinstance(self.f_builtins, types.ModuleType):
            self.f_builtins = self.f_builtins.__dict__
        if self.f_builtins is None:
            self.f_builtins = {'None': None}

        self.stack = []

        self.f_lineno = f_code.co_firstlineno # XXX doesn't get updated
        self.f_lasti = 0

        self.cells = {} if f_code.co_cellvars or f_code.co_freevars else None
        for var in f_code.co_cellvars:
            self.cells[var] = Cell(self.f_locals.get(var))
        if f_code.co_freevars:
            assert len(f_code.co_freevars) == len(f_closure)
            self.cells.update(zip(f_code.co_freevars, f_closure))
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def load_session(fname=None):
    if conf.interactive_shell.lower() == "ipython":
        log_interactive.error("There are issues with load_session in ipython. Use python for interactive shell, or use -s parameter to load session")    
        return

    import dill as pickle

    if fname is None:
        fname = conf.session
    try:
        s = pickle.load(gzip.open(fname,"rb"))
    except IOError:
        s = pickle.load(open(fname,"rb"))
    scapy_session = builtins.__dict__["scapy_session"]
    scapy_session.clear()
    scapy_session.update(s)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
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
项目:execnet    作者:pytest-dev    | 项目源码 | 文件源码
def _find_non_builtin_globals(source, codeobj):
    try:
        import ast
    except ImportError:
        return None
    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__
    ]
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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 [builtins.__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
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def load_session(fname=None):
    if conf.interactive_shell.lower() == "ipython":
        log_interactive.error("There are issues with load_session in ipython. Use python for interactive shell, or use -s parameter to load session")    
        return

    import dill as pickle

    if fname is None:
        fname = conf.session
    try:
        s = pickle.load(gzip.open(fname,"rb"))
    except IOError:
        s = pickle.load(open(fname,"rb"))
    scapy_session = builtins.__dict__["scapy_session"]
    scapy_session.clear()
    scapy_session.update(s)
项目:Tencent_Cartoon_Download    作者:Fretice    | 项目源码 | 文件源码
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, builtins.__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
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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, builtins.__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
项目:specto    作者:mrknow    | 项目源码 | 文件源码
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)
项目:specto    作者:mrknow    | 项目源码 | 文件源码
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)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def getmembers(object, predicate=None):
    """Return all members of an object as (name, value) pairs sorted by name.
    Optionally, only return members that satisfy a given predicate."""
    if isclass(object):
        mro = (object,) + getmro(object)
    else:
        mro = ()
    results = []
    for key in dir(object):
        # First try to get the value via __dict__. Some descriptors don't
        # like calling their __get__ (see bug #1785).
        for base in mro:
            if key in base.__dict__:
                value = base.__dict__[key]
                break
        else:
            try:
                value = getattr(object, key)
            except AttributeError:
                continue
        if not predicate or predicate(value):
            results.append((key, value))
    results.sort()
    return results
项目:CloudPrint    作者:William-An    | 项目源码 | 文件源码
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 not text.strip():
            if state == 0:
                return '\t'
            else:
                return None

        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
项目:CloudPrint    作者:William-An    | 项目源码 | 文件源码
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 [builtins.__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
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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 not text.strip():
            if state == 0:
                return '\t'
            else:
                return None

        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
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
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, builtins.__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
项目:gardenbot    作者:GoestaO    | 项目源码 | 文件源码
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, builtins.__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
项目:projeto    作者:BarmyPenguin    | 项目源码 | 文件源码
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 not text.strip():
            if state == 0:
                return '\t'
            else:
                return None

        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
项目:projeto    作者:BarmyPenguin    | 项目源码 | 文件源码
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 [builtins.__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
项目:flask-zhenai-mongo-echarts    作者:Fretice    | 项目源码 | 文件源码
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, builtins.__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
项目:teleport    作者:eomsoft    | 项目源码 | 文件源码
def __init__(self):
        if '__teleport_db__' in builtins.__dict__:
            raise RuntimeError('TPDatabase object exists, you can not create more than one instance.')

        self.db_type = self.DB_TYPE_UNKNOWN
        self.sqlite_file = ''
        self.mysql_host = ''
        self.mysql_port = 0
        self.mysql_db = ''
        self.mysql_user = ''
        self.mysql_password = ''

        self.need_create = False  # ???????????
        self.need_upgrade = False  # ????????????????
        self.current_ver = 0

        self.auto_increment = ''

        self._table_prefix = ''
        self._conn_pool = None
项目:teleport    作者:eomsoft    | 项目源码 | 文件源码
def __init__(self, **kwargs):
        super().__init__(**kwargs)

        import builtins
        if '__web_config__' in builtins.__dict__:
            raise RuntimeError('WebConfig object exists, you can not create more than one instance.')

        self['core'] = AttrDict()
        self['core']['detected'] = False
        # self['core']['ssh'] = AttrDict()
        # self['core']['ssh']['enable'] = False
        # self['core']['ssh']['port'] = 0  # 52189
        # self['core']['rdp'] = AttrDict()
        # self['core']['rdp']['enable'] = False
        # self['core']['rdp']['port'] = 0  # 52089
        # self['core']['telnet'] = AttrDict()
        # self['core']['telnet']['enable'] = False
        # self['core']['telnet']['port'] = 0  # 52389
项目:aweasome_learning    作者:Knight-ZXW    | 项目源码 | 文件源码
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 not text.strip():
            if state == 0:
                return '\t'
            else:
                return None

        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
项目:aweasome_learning    作者:Knight-ZXW    | 项目源码 | 文件源码
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 [builtins.__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
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
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 [builtins.__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
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def load_session(fname=None):
    if conf.interactive_shell.lower() == "ipython":
        log_interactive.error("There are issues with load_session in ipython. Use python for interactive shell, or use -s parameter to load session")    
        return

    import dill as pickle

    if fname is None:
        fname = conf.session
    try:
        s = pickle.load(gzip.open(fname,"rb"))
    except IOError:
        s = pickle.load(open(fname,"rb"))
    scapy_session = builtins.__dict__["scapy_session"]
    scapy_session.clear()
    scapy_session.update(s)
项目:blog_flask    作者:momantai    | 项目源码 | 文件源码
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, builtins.__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
项目:gmx    作者:pslacerda    | 项目源码 | 文件源码
def system(dir):
    prevdir = path.abspath('.')
    try:
        os.mkdir(dir)
    except FileExistsError:
        pass
    os.chdir(dir)

    env = PrettyCheckpointedEnvironment()
    factories = gromacs_command_factory()
    for fancy, name, factory in factories:
        def runner(name=name, factory=factory, **kwargs):
            cmd = factory(name, **kwargs)
            env.run_command(cmd)
        builtins.__dict__[fancy] = runner

    yield

    os.chdir(prevdir)
    for fancy, _, _ in factories:
        del builtins.__dict__[fancy]
项目:MyFriend-Rob    作者:lcheniv    | 项目源码 | 文件源码
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, builtins.__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
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
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
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def __init__(self, namespace = None):
        """Create a new completer for the command line.

        Completer([namespace]) -> completer instance.

        If unspecified, the default namespace where completions are performed
        is __main__ (technically, __main__.__dict__). Namespaces should be
        given as dictionaries.

        Completer instances should be used as the completion mechanism of
        readline via the set_completer() call:

        readline.set_completer(Completer(my_namespace).complete)
        """

        if namespace and not isinstance(namespace, dict):
            raise TypeError('namespace must be a dictionary')

        # Don't bind to namespace quite yet, but flag whether the user wants a
        # specific namespace or to use __main__.__dict__. This will allow us
        # to bind to __main__.__dict__ at completion time, not now.
        if namespace is None:
            self.use_main_ns = 1
        else:
            self.use_main_ns = 0
            self.namespace = namespace
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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 not text.strip():
            if state == 0:
                if _readline_available:
                    readline.insert_text('\t')
                    readline.redisplay()
                    return ''
                else:
                    return '\t'
            else:
                return None

        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
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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)
                if word in {'finally', 'try'}:
                    word = word + ':'
                elif word not in {'False', 'None', 'True',
                                  'break', 'continue', 'pass',
                                  'else'}:
                    word = word + ' '
                matches.append(word)
        for nspace in [self.namespace, builtins.__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
项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def __init__(self, name, code, globs, defaults, closure):
        self.__name__ = name or code.co_name
        self.__code__ = code
        self.__globals__ = globs
        self.__defaults__ = tuple(defaults)
        self.__closure__ = closure
        self.__dict__ = {}
        self.__doc__ = code.co_consts[0] if code.co_consts else None
项目:tailbiter    作者:darius    | 项目源码 | 文件源码
def run(code, f_globals, f_locals):
    if f_globals is None: f_globals = builtins.globals()
    if f_locals is None:  f_locals = f_globals
    if '__builtins__' not in f_globals:
        f_globals['__builtins__'] = builtins.__dict__
    return run_frame(code, None, f_globals, f_locals)
项目:ivaochdoc    作者:ivaoch    | 项目源码 | 文件源码
def __init__(self, namespace = None):
        """Create a new completer for the command line.

        Completer([namespace]) -> completer instance.

        If unspecified, the default namespace where completions are performed
        is __main__ (technically, __main__.__dict__). Namespaces should be
        given as dictionaries.

        Completer instances should be used as the completion mechanism of
        readline via the set_completer() call:

        readline.set_completer(Completer(my_namespace).complete)
        """

        if namespace and not isinstance(namespace, dict):
            raise TypeError('namespace must be a dictionary')

        # Don't bind to namespace quite yet, but flag whether the user wants a
        # specific namespace or to use __main__.__dict__. This will allow us
        # to bind to __main__.__dict__ at completion time, not now.
        if namespace is None:
            self.use_main_ns = 1
        else:
            self.use_main_ns = 0
            self.namespace = namespace
项目:ivaochdoc    作者:ivaoch    | 项目源码 | 文件源码
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 not text.strip():
            if state == 0:
                if _readline_available:
                    readline.insert_text('\t')
                    readline.redisplay()
                    return ''
                else:
                    return '\t'
            else:
                return None

        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
项目:ivaochdoc    作者:ivaoch    | 项目源码 | 文件源码
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)
                if word in {'finally', 'try'}:
                    word = word + ':'
                elif word not in {'False', 'None', 'True',
                                  'break', 'continue', 'pass',
                                  'else'}:
                    word = word + ' '
                matches.append(word)
        for nspace in [self.namespace, builtins.__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
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def _load(module):
    try:
        mod = __import__(module,globals(),locals(),".")
        builtins.__dict__.update(mod.__dict__)
    except Exception as e:
        log_interactive.error(e)
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def save_session(fname=None, session=None, pickleProto=4):
    import dill as pickle

    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 = builtins.__dict__["scapy_session"]

    to_be_saved = session.copy()

    for k in list(to_be_saved.keys()):
        if k in ["__builtins__", "In", "Out", "conf"] or k.startswith("_") or \
                (hasattr(to_be_saved[k], "__module__") and str(to_be_saved[k].__module__).startswith('IPython')):
            del(to_be_saved[k])
            continue
        if type(to_be_saved[k]) in [type, types.ModuleType, types.MethodType]:
             log_interactive.info("[%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")
    for i in to_be_saved.keys():
        #d = {i: to_be_saved[i]}
        #pickle.dump(d, f, pickleProto)
        pickle.dump(to_be_saved, f, pickleProto)
    f.close()
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def update_session(fname=None):
    import dill as pickle
    if fname is None:
        fname = conf.session
    try:
        s = pickle.load(gzip.open(fname,"rb"))
    except IOError:
        s = pickle.load(open(fname,"rb"))
    scapy_session = builtins.__dict__["scapy_session"]
    scapy_session.update(s)


################
##### Main #####
################
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def autorun_commands(cmds,my_globals=None,verb=0):
    sv = conf.verb
    import builtins
    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()
            builtins.__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 _
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
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
        builtin_mod.__dict__['display'] = display

        self.builtin_trap = BuiltinTrap(shell=self)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def new_main_mod(self, filename, modname):
        """Return a new 'main' module object for user code execution.

        ``filename`` should be the path of the script which will be run in the
        module. Requests with the same filename will get the same module, with
        its namespace cleared.

        ``modname`` should be the module name - normally either '__main__' or
        the basename of the file without the extension.

        When scripts are executed via %run, we must keep a reference to their
        __main__ module around so that Python doesn't
        clear it, rendering references to module globals useless.

        This method keeps said reference in a private dict, keyed by the
        absolute path of the script. This way, for multiple executions of the
        same script we only keep one copy of the namespace (the last one),
        thus preventing memory leaks from old references while allowing the
        objects from the last execution to be accessible.
        """
        filename = os.path.abspath(filename)
        try:
            main_mod = self._main_mod_cache[filename]
        except KeyError:
            main_mod = self._main_mod_cache[filename] = types.ModuleType(
                        modname,
                        doc="Module created for script run in IPython")
        else:
            main_mod.__dict__.clear()
            main_mod.__name__ = modname

        main_mod.__file__ = filename
        # It seems pydoc (and perhaps others) needs any module instance to
        # implement a __nonzero__ method
        main_mod.__nonzero__ = lambda : True

        return main_mod
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def all_ns_refs(self):
        """Get a list of references to all the namespace dictionaries in which
        IPython might store a user-created object.

        Note that this does not include the displayhook, which also caches
        objects from the output."""
        return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
               [m.__dict__ for m in self._main_mod_cache.values()]
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def add_builtin(self, key, value):
        """Add a builtin and save the original."""
        bdict = builtin_mod.__dict__
        orig = bdict.get(key, BuiltinUndefined)
        if value is HideBuiltin:
            if orig is not BuiltinUndefined: #same as 'key in bdict'
                self._orig_builtins[key] = orig
                del bdict[key]
        else:
            self._orig_builtins[key] = orig
            bdict[key] = value
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def remove_builtin(self, key, orig):
        """Remove an added builtin and re-set the original."""
        if orig is BuiltinUndefined:
            del builtin_mod.__dict__[key]
        else:
            builtin_mod.__dict__[key] = orig
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def check_for_underscore(self):
        """Check if the user has set the '_' variable by hand."""
        # If something injected a '_' variable in __builtin__, delete
        # ipython's automatic one so we don't clobber that.  gettext() in
        # particular uses _, so we need to stay away from it.
        if '_' in builtin_mod.__dict__:
            try:
                user_value = self.shell.user_ns['_']
                if user_value is not self._:
                    return
                del self.shell.user_ns['_']
            except KeyError:
                pass
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def update_user_ns(self, result):
        """Update user_ns with various things like _, __, _1, etc."""

        # Avoid recursive reference when displaying _oh/Out
        if result is not self.shell.user_ns['_oh']:
            if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
                self.cull_cache()

            # Don't overwrite '_' and friends if '_' is in __builtin__
            # (otherwise we cause buggy behavior for things like gettext). and
            # do not overwrite _, __ or ___ if one of these has been assigned
            # by the user.
            update_unders = True
            for unders in ['_'*i for i in range(1,4)]:
                if not unders in self.shell.user_ns:
                    continue
                if getattr(self, unders) is not self.shell.user_ns.get(unders):
                    update_unders = False

            self.___ = self.__
            self.__ = self._
            self._ = result

            if ('_' not in builtin_mod.__dict__) and (update_unders):
                self.shell.push({'_':self._,
                                 '__':self.__,
                                '___':self.___}, interactive=False)

            # hackish access to top-level  namespace to create _1,_2... dynamically
            to_main = {}
            if self.do_full_cache:
                new_result = '_%s' % self.prompt_count
                to_main[new_result] = result
                self.shell.push(to_main, interactive=False)
                self.shell.user_ns['_oh'][self.prompt_count] = result