• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python gateway.applevel函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: fake_code

app = gateway.applevel('''
"NOT_RPYTHON"
import __builtin__

class fake_code(object):
    co_name = "?"
    co_filename = "?"
    co_firstlineno = 0

class fake_frame(object):
    f_back = None
    f_builtins = __builtin__.__dict__
    f_code = fake_code()
    f_exc_traceback = None
    f_exc_type = None
    f_exc_value = None
    f_globals = {}
    f_lasti = -1
    f_lineno = 0
    f_locals = {}
    f_restricted = False
    f_trace = None

    def __init__(self, f):
        if f is not None:
            for name in ["f_builtins", "f_code", "f_globals", "f_lasti",
                         "f_lineno"]:
                setattr(self, name, getattr(f, name))
''')
开发者ID:Debug-Orz,项目名称:Sypy,代码行数:29,代码来源:currentframes.py


示例17: possint

    #w_real = space.call_function(space.w_float,space.wrap(w_self.realval))
    #w_imag = space.call_function(space.w_float,space.wrap(-w_self.imagval))
    return space.newcomplex(w_self.realval,-w_self.imagval)

app = gateway.applevel(""" 
    import math
    def possint(f):
        ff = math.floor(f)
        if f == ff:
            return int(ff)
        return f

    def repr__Complex(f):
        if not f.real:
            return repr(possint(f.imag))+'j'
        imag = f.imag
        sign = ((imag >= 0) and '+') or ''
        return '('+repr(possint(f.real)) + sign + repr(possint(f.imag))+'j)'

    def str__Complex(f):
        if not f.real:
            return str(possint(f.imag))+'j'
        imag = f.imag
        sign = ((imag >= 0) and '+') or ''
        return '('+str(possint(f.real)) + sign + str(possint(f.imag))+'j)'

""", filename=__file__) 

repr__Complex = app.interphook('repr__Complex') 
str__Complex = app.interphook('str__Complex') 
开发者ID:antoine1fr,项目名称:pygirl,代码行数:30,代码来源:complexobject.py


示例18: makefile

        Decrease the usecount of the socketobject. If the
        usecount reaches 0 close the socket.
        Intended only to be used by socket._socketobject
        """
        self.usecount -= 1
        if self.usecount > 0:
            return
        self.close_w(space)
    _drop_w.unwrap_spec = ['self', ObjSpace]

app_makefile = gateway.applevel(r'''
def makefile(self, mode="r", buffersize=-1):
    """makefile([mode[, buffersize]]) -> file object

    Return a regular file object corresponding to the socket.
    The mode and buffersize arguments are as for the built-in open() function.
    """
    import os
    newfd = os.dup(self.fileno())
    return os.fdopen(newfd, mode, buffersize)
''', filename =__file__).interphook('makefile')

def newsocket(space, w_subtype, family=AF_INET,
              type=SOCK_STREAM, proto=0):
    # XXX If we want to support subclassing the socket type we will need
    # something along these lines. But allocate_instance is only defined
    # on the standard object space, so this is not really correct.
    #sock = space.allocate_instance(W_RSocket, w_subtype)
    #Socket.__init__(sock, space, fd, family, type, proto)
    try:
        sock = W_RSocket(family, type, proto)
开发者ID:TheDunn,项目名称:flex-pypy,代码行数:31,代码来源:interp_socket.py


示例19: unicode_from_encoded_object

app = gateway.applevel('''
def unicode_from_encoded_object(obj, encoding, errors):
    import codecs, sys
    if encoding is None:
        encoding = sys.getdefaultencoding()
    decoder = codecs.getdecoder(encoding)
    if errors is None:
        retval, length = decoder(obj)
    else:
        retval, length = decoder(obj, errors)
    if not isinstance(retval, unicode):
        raise TypeError("decoder did not return an unicode object (type=%s)" %
                        type(retval).__name__)
    return retval

def unicode_from_object(obj):
    if isinstance(obj, str):
        res = obj
    else:
        try:
            unicode_method = obj.__unicode__
        except AttributeError:
            res = str(obj)
        else:
            res = unicode_method()
    if isinstance(res, unicode):
        return res
    return unicode_from_encoded_object(res, None, "strict")
    
''')
unicode_from_object = app.interphook('unicode_from_object')
开发者ID:TheDunn,项目名称:flex-pypy,代码行数:31,代码来源:unicodetype.py


示例20: OperationError

    if not w_newcls.is_heaptype():
        raise OperationError(space.w_TypeError,
                             space.wrap("__class__ assignment: only for heap types"))
    w_oldcls = space.type(w_obj)
    assert isinstance(w_oldcls, W_TypeObject)
    if w_oldcls.get_full_instance_layout() == w_newcls.get_full_instance_layout():
        w_obj.setclass(space, w_newcls)
    else:
        raise operationerrfmt(space.w_TypeError,
                              "__class__ assignment: '%s' object layout differs from '%s'",
                              w_oldcls.getname(space), w_newcls.getname(space))


app = gateway.applevel("""
def _abstract_method_error(typ):
    methods = ", ".join(sorted(typ.__abstractmethods__))
    err = "Can't instantiate abstract class %s with abstract methods %s"
    raise TypeError(err % (typ.__name__, methods))
""")
_abstract_method_error = app.interphook("_abstract_method_error")


def descr__new__(space, w_type, __args__):
    from pypy.objspace.std.objectobject import W_ObjectObject
    from pypy.objspace.std.typetype import _precheck_for_new
    # don't allow arguments if the default object.__init__() is about
    # to be called
    w_type = _precheck_for_new(space, w_type)
    w_parentinit, w_ignored = w_type.lookup_where('__init__')
    if w_parentinit is space.w_object:
        try:
            __args__.fixedunpack(0)
开发者ID:Debug-Orz,项目名称:Sypy,代码行数:32,代码来源:objecttype.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python gateway.interp2app函数代码示例发布时间:2022-05-27
下一篇:
Python gateway.app2interp_temp函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap