当前位置: 首页>>代码示例>>Python>>正文


Python gateway.applevel函数代码示例

本文整理汇总了Python中pypy.interpreter.gateway.applevel函数的典型用法代码示例。如果您正苦于以下问题:Python applevel函数的具体用法?Python applevel怎么用?Python applevel使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了applevel函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getappfileloader

def getappfileloader(pkgroot, appname, spec):
    """ NOT_RPYTHON """
    # hum, it's a bit more involved, because we usually
    # want the import at applevel
    modname, attrname = spec.split(".")
    impbase = pkgroot + "." + modname
    try:
        app = applevelcache[impbase]
    except KeyError:
        import imp

        pkg = __import__(pkgroot, None, None, ["__doc__"])
        file, fn, (suffix, mode, typ) = imp.find_module(modname, pkg.__path__)
        assert typ == imp.PY_SOURCE
        source = file.read()
        file.close()
        if fn.endswith(".pyc") or fn.endswith(".pyo"):
            fn = fn[:-1]
        app = gateway.applevel(source, filename=fn, modname=appname)
        applevelcache[impbase] = app

    def afileloader(space):
        return app.wget(space, attrname)

    return afileloader
开发者ID:kipras,项目名称:pypy,代码行数:25,代码来源:mixedmodule.py

示例2: get_entry_point

    def get_entry_point(self, config):
        space = make_objspace(config)

        # manually imports app_main.py
        filename = os.path.join(pypydir, 'interpreter', 'app_main.py')
        app = gateway.applevel(open(filename).read(), 'app_main.py', 'app_main')
        app.hidden_applevel = False
        w_dict = app.getwdict(space)
        entry_point, _ = create_entry_point(space, w_dict)

        return entry_point, None, PyPyAnnotatorPolicy()
开发者ID:mozillazg,项目名称:pypy,代码行数:11,代码来源:targetpypystandalone.py

示例3: get_entry_point

    def get_entry_point(self, config):
        from pypy.tool.lib_pypy import import_from_lib_pypy
        rebuild = import_from_lib_pypy('ctypes_config_cache/rebuild')
        rebuild.try_rebuild()

        space = make_objspace(config)

        # manually imports app_main.py
        filename = os.path.join(pypydir, 'interpreter', 'app_main.py')
        app = gateway.applevel(open(filename).read(), 'app_main.py', 'app_main')
        app.hidden_applevel = False
        w_dict = app.getwdict(space)
        entry_point, _ = create_entry_point(space, w_dict)

        return entry_point, None, PyPyAnnotatorPolicy()
开发者ID:timfel,项目名称:thesis-data,代码行数:15,代码来源:targetpypystandalone.py

示例4: exprcompile

            return exprcompile(space, w_compileAST)
        else:
            return modcompile(space, w_compileAST)
    descr_compile.unwrap_spec = ['self', ObjSpace, str]

ASTType = STType

app = applevel("""
    def mycompile(tup, filename):
        import compiler
        transformer = compiler.transformer.Transformer()
        compileAST = transformer.compile_node(tup)
        compiler.misc.set_filename(filename, compileAST)
        return compileAST

    def exprcompile(compileAST):
        import compiler
        gen = compiler.pycodegen.ExpressionCodeGenerator(compileAST)
        return gen.getCode()

    def modcompile(compileAST):
        import compiler
        gen = compiler.pycodegen.ModuleCodeGenerator(compileAST)
        return gen.getCode()
""", filename=__file__)

mycompile = app.interphook("mycompile")
exprcompile = app.interphook("exprcompile")
modcompile = app.interphook("modcompile")

STType.typedef = TypeDef("parser.st",
    compile = interp2app(STType.descr_compile),
开发者ID:AishwaryaKM,项目名称:python-tutorial,代码行数:32,代码来源:pyparser.py

示例5: dict_get__Dict_ANY_ANY

def dict_get__Dict_ANY_ANY(space, w_dict, w_lookup, w_default):
    return w_dict.content.get(w_lookup, w_default)

app = gateway.applevel('''
    def dictrepr(currently_in_repr, d):
        # Now we only handle one implementation of dicts, this one.
        # The fix is to move this to dicttype.py, and do a
        # multimethod lookup mapping str to StdObjSpace.str
        # This cannot happen until multimethods are fixed. See dicttype.py
            dict_id = id(d)
            if dict_id in currently_in_repr:
                return '{...}'
            currently_in_repr[dict_id] = 1
            try:
                items = []
                # XXX for now, we cannot use iteritems() at app-level because
                #     we want a reasonable result instead of a RuntimeError
                #     even if the dict is mutated by the repr() in the loop.
                for k, v in dict.items(d):
                    items.append(repr(k) + ": " + repr(v))
                return "{" +  ', '.join(items) + "}"
            finally:
                try:
                    del currently_in_repr[dict_id]
                except:
                    pass
''', filename=__file__)

dictrepr = app.interphook("dictrepr")

def repr__Dict(space, w_dict):
开发者ID:AishwaryaKM,项目名称:python-tutorial,代码行数:31,代码来源:dictobject.py

示例6: get_float_info

from rpython.rlib import rbigint, rfloat
from rpython.rtyper.lltypesystem import rffi


app = gateway.applevel("""
"NOT_RPYTHON"
from _structseq import structseqtype, structseqfield
class float_info:
    __metaclass__ = structseqtype

    max = structseqfield(0)
    max_exp = structseqfield(1)
    max_10_exp = structseqfield(2)
    min = structseqfield(3)
    min_exp = structseqfield(4)
    min_10_exp = structseqfield(5)
    dig = structseqfield(6)
    mant_dig = structseqfield(7)
    epsilon = structseqfield(8)
    radix = structseqfield(9)
    rounds = structseqfield(10)

class long_info:
    __metaclass__ = structseqtype
    bits_per_digit = structseqfield(0)
    sizeof_digit = structseqfield(1)
""")


def get_float_info(space):
    info_w = [
开发者ID:mozillazg,项目名称:pypy,代码行数:31,代码来源:system.py

示例7: script

               "library module to be run as a script (terminates option list)",
               default=False, cmdline="-m"),
    BoolOption("runcommand",
               "program passed in as CMD (terminates option list)",
               default=False, cmdline="-c"),
    StrOption("warn",
              "warning control (arg is action:message:category:module:lineno)",
              default=None, cmdline="-W"),
 
    ])

pypy_init = gateway.applevel('''
def pypy_init(import_site):
    if import_site:
        try:
            import site
        except:
            import sys
            print("'import site' failed", file=sys.stderr)
''').interphook('pypy_init')


def set_compiler(option, opt, value, parser):
    from rpython.translator.platform import set_platform
    set_platform('host', value)

def main_(argv=None):
    starttime = time.time()
    config, parser = option.get_standard_options()
    interactiveconfig = Config(cmdline_optiondescr)
    to_optparse(interactiveconfig, parser=parser)
开发者ID:Qointum,项目名称:pypy,代码行数:31,代码来源:pyinteractive.py

示例8: eq__Type_Type

                          "type object '%s' has no attribute '%s'",
                          w_type.name, name)

def eq__Type_Type(space, w_self, w_other):
    return space.is_(w_self, w_other)

# ____________________________________________________________


abstract_mro = gateway.applevel("""
    def abstract_mro(klass):
        # abstract/classic mro
        mro = []
        stack = [klass]
        while stack:
            klass = stack.pop()
            if klass not in mro:
                mro.append(klass)
                if not isinstance(klass.__bases__, tuple):
                    raise TypeError, '__bases__ must be a tuple'
                stack += klass.__bases__[::-1]
        return mro
""", filename=__file__).interphook("abstract_mro")

def get_mro(space, klass):
    if isinstance(klass, W_TypeObject):
        return list(klass.mro_w)
    else:
        return space.unpackiterable(abstract_mro(space, klass))


def compute_C3_mro(space, cls):
开发者ID:Debug-Orz,项目名称:Sypy,代码行数:32,代码来源:typeobject.py

示例9: list

        else:
            # Make a shallow copy to more easily handle the reversal case
            sequence2 = list(sequence2)
    for i in range(len2):
        items[start] = sequence2[i]
        start += step
    return space.w_None

app = gateway.applevel("""
    def listrepr(currently_in_repr, l):
        'The app-level part of repr().'
        list_id = id(l)
        if list_id in currently_in_repr:
            return '[...]'
        currently_in_repr[list_id] = 1
        try:
            return "[" + ", ".join([repr(x) for x in l]) + ']'
        finally:
            try:
                del currently_in_repr[list_id]
            except:
                pass
""", filename=__file__) 

listrepr = app.interphook("listrepr")

def repr__List(space, w_list):
    if len(w_list.wrappeditems) == 0:
        return space.wrap('[]')
    w_currently_in_repr = space.getexecutioncontext()._py_repr
    return listrepr(space, w_currently_in_repr, w_list)
开发者ID:TheDunn,项目名称:flex-pypy,代码行数:31,代码来源:listobject.py

示例10: setattr

        setattr(W_DictMultiObject, method, make_method(method))

_add_indirections()


app = applevel('''
    def dictrepr(currently_in_repr, d):
        if len(d) == 0:
            return "{}"
        dict_id = id(d)
        if dict_id in currently_in_repr:
            return '{...}'
        currently_in_repr[dict_id] = 1
        try:
            items = []
            # XXX for now, we cannot use iteritems() at app-level because
            #     we want a reasonable result instead of a RuntimeError
            #     even if the dict is mutated by the repr() in the loop.
            for k, v in dict.items(d):
                items.append(repr(k) + ": " + repr(v))
            return "{" +  ', '.join(items) + "}"
        finally:
            try:
                del currently_in_repr[dict_id]
            except:
                pass
''', filename=__file__)

dictrepr = app.interphook("dictrepr")


W_DictMultiObject.typedef = StdTypeDef("dict",
开发者ID:charred,项目名称:pypy,代码行数:32,代码来源:dictmultiobject.py

示例11: syntax_warning

from pypy.interpreter import gateway
from rpython.rlib.objectmodel import we_are_translated
from rpython.rlib.unroll import unrolling_iterable


app = gateway.applevel("""
def syntax_warning(msg, fn, lineno, offset):
    import warnings
    try:
        warnings.warn_explicit(msg, SyntaxWarning, fn, lineno)
    except SyntaxWarning:
        raise SyntaxError(msg, fn, lineno, offset)
""", filename=__file__)
_emit_syntax_warning = app.interphook("syntax_warning")
del app

def syntax_warning(space, msg, fn, lineno, offset):
    """Raise an applevel SyntaxWarning.

    If the user has set this warning to raise an error, a SyntaxError will be
    raised."""
    w_msg = space.wrap(msg)
    w_filename = space.wrap(fn)
    w_lineno = space.wrap(lineno)
    w_offset = space.wrap(offset)
    _emit_syntax_warning(space, w_msg, w_filename, w_lineno, w_offset)


def parse_future(tree, feature_flags):
    from pypy.interpreter.astcompiler import ast
    future_lineno = 0
开发者ID:Darriall,项目名称:pypy,代码行数:31,代码来源:misc.py

示例12: applevel

the few needed functions are implemented in a tiny os module
that contains a tiny path module.

os.getenv got a direct implementation to overcome the caching
problem.

Please adjust the applevel code below, if you need to support
more from os and os.path.
"""

from pypy.interpreter.gateway import applevel, ObjSpace, W_Root, interp2app
import os

app_os_path = applevel(
    r"""
    from os.path import dirname, join, abspath, isfile, islink
""",
    filename=__file__,
)

app_os = applevel(
    r"""
    from os import sep, pathsep, getenv, name, fdopen
    try:
        from os import readlink
    except ImportError:
        pass
""",
    filename=__file__,
)

开发者ID:alkorzt,项目名称:pypy,代码行数:30,代码来源:nanos.py

示例13: hasattr

app = gateway.applevel('''

    # in the following functions we use dict.__setitem__ instead of
    # d[k]=...  because when a subclass of dict override __setitem__,
    # CPython does not call it when doing builtin operations.  The
    # same for other operations.

    def update1(d, o):
        if hasattr(o, 'keys'):
            for k in o.keys():
                dict.__setitem__(d, k, o[k])
        else:
            for k,v in o:
                dict.__setitem__(d, k, v)

    def update(d, *args, **kwargs):
        len_args = len(args)
        if len_args == 1:
            update1(d, args[0])
        elif len_args > 1:
            raise TypeError("update takes at most 1 (non-keyword) argument")
        if kwargs:
            update1(d, kwargs)

    def popitem(d):
        for k in dict.iterkeys(d):
            break
        else:
            raise KeyError("popitem(): dictionary is empty")
        v = dict.__getitem__(d, k)
        dict.__delitem__(d, k)
        return k, v

    def get(d, k, v=None):
        if k in d:
            return dict.__getitem__(d, k)
        else:
            return v

    def setdefault(d, k, v=None):
        if k in d:
            return dict.__getitem__(d, k)
        else:
            dict.__setitem__(d, k, v)
            return v

    def pop(d, k, defaults):     # XXX defaults is actually *defaults
        if len(defaults) > 1:
            raise TypeError, "pop expected at most 2 arguments, got %d" % (
                1 + len(defaults))
        try:
            v = dict.__getitem__(d, k)
            dict.__delitem__(d, k)
        except KeyError, e:
            if defaults:
                return defaults[0]
            else:
                raise e
        return v

    def iteritems(d):
        return iter(dict.items(d))

    def iterkeys(d):
        return iter(dict.keys(d))

    def itervalues(d):
        return iter(dict.values(d))
''', filename=__file__)
开发者ID:AishwaryaKM,项目名称:python-tutorial,代码行数:69,代码来源:dicttype.py

示例14: isinf

    if isinf(z):
        raise oefmt(space.w_OverflowError,
                    "rounded value too large to represent")
    return space.wrap(z)

# ____________________________________________________________

iter_sentinel = gateway.applevel('''
    # NOT_RPYTHON  -- uses yield
    # App-level implementation of the iter(callable,sentinel) operation.

    def iter_generator(callable_, sentinel):
        while 1:
            result = callable_()
            if result == sentinel:
                return
            yield result

    def iter_sentinel(callable_, sentinel):
        if not callable(callable_):
            raise TypeError, 'iter(v, w): v must be callable'
        return iter_generator(callable_, sentinel)

''', filename=__file__).interphook("iter_sentinel")

def iter(space, w_collection_or_callable, w_sentinel=None):
    """iter(collection) -> iterator over the elements of the collection.

iter(callable, sentinel) -> iterator calling callable() until it returns
                            the sentinal.
"""
开发者ID:mozillazg,项目名称:pypy,代码行数:31,代码来源:operation.py

示例15: BoolOption

               default=False, cmdline="-O"),
    BoolOption("no_site_import", "do not 'import site' on initialization",
               default=False, cmdline="-S"),
    StrOption("runmodule",
              "library module to be run as a script (terminates option list)",
              default=None, cmdline="-m"),
    StrOption("runcommand",
              "program passed in as CMD (terminates option list)",
              default=None, cmdline="-c"),
    ])

pypy_init = gateway.applevel('''
def pypy_init(import_site):
    if import_site:
        try:
            import site
        except:
            import sys
            print >> sys.stderr, "import site\' failed"
''').interphook('pypy_init')

def getenv_w(space, name):
    w_os = space.getbuiltinmodule('os')
    w_environ = space.getattr(w_os, space.wrap('environ'))
    w_v = space.call_method(w_environ, 'get', space.wrap(name))
    try:
        return space.str_w(w_v)
    except:
        return None

开发者ID:TheDunn,项目名称:flex-pypy,代码行数:29,代码来源:py.py


注:本文中的pypy.interpreter.gateway.applevel函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。