コード例 #1
0
ファイル: module.py プロジェクト: BackupTheBerlios/empath-svn
def fromfile(path): #{{{
    pypath = absmodpath(path)
    if not pypath:
        raise TypeError("Not a valid python file: %s" %path)
    mod, isdir = None, op.isdir
    rootdir, osj, j = pkgdir(path), op.join, '.'.join
    path_isdir = isdir(path)
    pypath_list = pypath.split('.')
    maxlen = len(pypath_list)
    if path_isdir:
        path = osj(path, hasinit(path))
    elif op.basename(path) in ('__init__.py%s' %s for s in ('', 'c', 'o')):
        path_isdir = True
    sysmod = sys.modules
    mod = sysmod.get(pypath)
    if mod and mod.__file__ == path:
        return mod
    for ind in xrange(1, maxlen+1):
        cur = pypath_list[:ind]
        ospath, name = osj(rootdir, *cur), j(cur)
        filename = path if ind == maxlen else osj(ospath, hasinit(ospath))
        mod = sysmod.get(name)
        if mod and mod.__file__ == filename:
            continue
        mod = module(name)
        mod.__file__ = filename
        execfile(filename, mod.__dict__)
        sysmod[name] = mod
        if ind < maxlen or path_isdir:
            mod.__path__ = [ospath]
    return mod
コード例 #2
0
    def makeGrammar(self, rules):
        """
        Produce a class from a collection of rules.

        @param rules: A mapping of names to rule bodies.
        """
        lines = list(itertools.chain(*[self._function(
            "def rule_%s(self):" % (name,),
            ["_locals = {'self': self}",
             "self.locals[%r] = _locals" % (name,)] + list(body)) + ['\n\n']
                                       for (name, body) in rules]))
        source = '\n'.join(self._suite(
            "class %s(%s):" %(self.name, self.superclass.__name__),
            lines))
        modname = "pymeta_grammar__"+self.name
        filename = "/pymeta_generated_code/"+modname+".py"
        mod = module(modname)
        mod.__dict__.update(self.globals)
        mod.__name__ = modname
        mod.__dict__[self.superclass.__name__] = self.superclass
        mod.__loader__ = GeneratedCodeLoader(source)
        code = compile(source, filename, "exec")
        eval(code, mod.__dict__)
        mod.__dict__[self.name].globals = self.globals
        sys.modules[modname] = mod
        linecache.getlines(filename, mod.__dict__)
        return mod.__dict__[self.name]
コード例 #3
0
ファイル: builder.py プロジェクト: 309972460/software
def moduleFromGrammar(source, className, modname, filename):
    mod = module(modname)
    mod.__name__ = modname
    mod.__loader__ = GeneratedCodeLoader(source)
    code = compile(source, filename, "exec")
    eval(code, mod.__dict__)
    sys.modules[modname] = mod
    linecache.getlines(filename, mod.__dict__)
    return mod
コード例 #4
0
ファイル: builder.py プロジェクト: MostAwesomeDude/parsley
def moduleFromGrammar(source, className, modname, filename):
    mod = module(modname)
    mod.__name__ = modname
    mod.__loader__ = GeneratedCodeLoader(source)
    code = compile(source, filename, "exec")
    eval(code, mod.__dict__)
    sys.modules[modname] = mod
    linecache.getlines(filename, mod.__dict__)
    return mod
コード例 #5
0
def modulize(klass):
    if not isinstance(klass, type):
        raise TypeError('Only types can be modulized')
    result = module(klass.__name__)
    for name in type.__dir__(klass):
        if name in DO_NOT_MODULIZE_NAMES:
            continue
        value = type.__getattribute__(klass, name)
        if type(value) in DO_NOT_MODULIZE_TYPES:
            continue
        module.__setattr__(result, name, value)
    return result
コード例 #6
0
ファイル: runtime.py プロジェクト: mythmon/monte
def eval(source, scope=jacklegScope, origin="__main"):
    name = uuid.uuid4().hex + '.py'
    mod = module(name)
    mod.__name__ = name
    mod._m_outerScope = scope
    pysrc, _, lastline = ecompile(source, scope, origin).rpartition('\n')
    pysrc = '\n'.join(["from monte import runtime as _monte",
                       pysrc,
                       "_m_evalResult = " + lastline])
    mod.__loader__ = GeneratedCodeLoader(pysrc)
    code = compile(pysrc, name, "exec")
    pyeval(code, mod.__dict__)
    sys.modules[name] = mod
    linecache.getlines(name, mod.__dict__)
    return mod._m_evalResult
コード例 #7
0
def datatype(cls):
    """
    usage:
    @datatype
    class List(metaclass=TypeMeta):
        Nil : ( )
        Cons : ("hd","tl")
    # then we get a module ,the module name is 'm_' + class <name>,
    # class List ,then module name is m_List, module has Nil,Cons,List
    """
    mod = module("m_" + cls.__name__, cls.__doc__)
    mod.__dict__.update(cls.__annotations__)
    mod.__dict__.update({cls.__name__: cls})
    sys.modules["m_" + cls.__name__] = mod
    return mod
コード例 #8
0
ファイル: runtime.py プロジェクト: mythmon/monte
def eval(source, scope=jacklegScope, origin="__main"):
    name = uuid.uuid4().hex + '.py'
    mod = module(name)
    mod.__name__ = name
    mod._m_outerScope = scope
    pysrc, _, lastline = ecompile(source, scope, origin).rpartition('\n')
    pysrc = '\n'.join([
        "from monte import runtime as _monte", pysrc,
        "_m_evalResult = " + lastline
    ])
    mod.__loader__ = GeneratedCodeLoader(pysrc)
    code = compile(pysrc, name, "exec")
    pyeval(code, mod.__dict__)
    sys.modules[name] = mod
    linecache.getlines(name, mod.__dict__)
    return mod._m_evalResult
コード例 #9
0
ファイル: builder.py プロジェクト: espinielli/pyometa
def moduleFromGrammar(tree, className, superclass, globalsDict):
    source = writePython(tree)
    modname = "pyometa_grammar__" + className
    filename = "/pyometa_generated_code/" + modname + ".py"
    mod = module(modname)
    mod.__dict__.update(globalsDict)
    mod.__name__ = modname
    mod.__dict__[superclass.__name__] = superclass
    mod.__dict__["GrammarBase"] = superclass
    mod.__loader__ = GeneratedCodeLoader(source)
    code = compile(source, filename, "exec")
    eval(code, mod.__dict__)
    mod.__dict__[className].globals = globalsDict
    sys.modules[modname] = mod
    linecache.getlines(filename, mod.__dict__)
    return mod.__dict__[className]
コード例 #10
0
def moduleFromGrammar(tree, className, superclass, globalsDict):
    source = writePython(tree)
    modname = "pymeta_grammar__" + className
    filename = "/pymeta_generated_code/" + modname + ".py"
    mod = module(modname)
    mod.__dict__.update(globalsDict)
    mod.__name__ = modname
    mod.__dict__[superclass.__name__] = superclass
    mod.__dict__["GrammarBase"] = superclass
    mod.__loader__ = GeneratedCodeLoader(source)
    code = compile(source, filename, "exec")
    eval(code, mod.__dict__)
    mod.__dict__[className].globals = globalsDict
    sys.modules[modname] = mod
    linecache.getlines(filename, mod.__dict__)
    cls = mod.__dict__[className]
    cls.source = source
    return cls
コード例 #11
0
ファイル: lptenv.py プロジェクト: Scemoon/lpts
def _create_module_and_parents(name):
    """
    创建一个moduls, 并且把所有的parents modules添加到sys.modulues
    @param name: Module name, such as 'lib.'.
	"""
    parts = name.split(".")
    # first create the top-level module
    parent = _create_module(parts[0])
    created_parts = [parts[0]]
    parts.pop(0)

    # now, create any remaining child modules
    while parts:
        child_name = parts.pop(0)
        module = types.module(child_name)
        setattr(parent, child_name, module)
        created_parts.append(child_name)
        sys.modules[".".join(created_parts)] = module
        parent = module
コード例 #12
0
ファイル: frompymeta.py プロジェクト: rosscdh/pybars
def moduleFromSource(source, className, superclass=None, globalsDict=None, registerModule=True):
    modname = "pymeta_grammar__" + className + "__" + str(next(next_filename))
    filename = "/pymeta_generated_code/" + modname + ".py"
    mod = module(modname)
    if globalsDict:
        mod.__dict__.update(globalsDict)
    mod.__name__ = modname
    if superclass:
        mod.__dict__[superclass.__name__] = superclass
        mod.__dict__["GrammarBase"] = superclass
    mod.__loader__ = GeneratedCodeLoader(source)
    code = compile(source, filename, "exec")
    eval(code, mod.__dict__)
    fullGlobals = dict(getattr(mod.__dict__[className], "globals", None) or {})
    fullGlobals.update(globalsDict)
    mod.__dict__[className].globals = fullGlobals
    if registerModule:
        sys.modules[modname] = mod
    linecache.getlines(filename, mod.__dict__)
    return mod.__dict__[className]
コード例 #13
0
ファイル: load.py プロジェクト: washort/monte
def eval(source, scope=None, origin="__main"):
    name = origin.encode('ascii')
    mod = module(name)
    mod.__name__ = name
    mod._m_outerScope = scope
    if source in COMPILE_CACHE:
        pysrc = COMPILE_CACHE[source].encode('ascii')
    else:
        pysrc, _, lastline = ecompile(source, scope, origin).rpartition('\n')
        pysrc = '\n'.join(["from monte.runtime import compiler_helpers as _monte",
                               pysrc.encode('utf-8'),
                               "_m_evalResult = " + lastline.encode('utf-8')])
    mod.__loader__ = GeneratedCodeLoader(pysrc)
    COMPILE_CACHE[source] = pysrc
    code = compile(pysrc, name, "exec")
    import __builtin__
    __builtin__.eval(code, mod.__dict__)
    sys.modules[name] = mod
    linecache.getlines(name, mod.__dict__)
    return mod._m_evalResult
コード例 #14
0
ファイル: frompymeta.py プロジェクト: wnyc/pybars
def moduleFromSource(source, className, superclass=None, globalsDict=None,
    registerModule=True):
    modname = "pymeta_grammar__" + className + "__" + str(next(next_filename))
    filename = "/pymeta_generated_code/" + modname + ".py"
    mod = module(modname)
    if globalsDict:
        mod.__dict__.update(globalsDict)
    mod.__name__ = modname
    if superclass:
        mod.__dict__[superclass.__name__] = superclass
        mod.__dict__["GrammarBase"] = superclass
    mod.__loader__ = GeneratedCodeLoader(source)
    code = compile(source, filename, "exec")
    eval(code, mod.__dict__)
    fullGlobals = dict(getattr(mod.__dict__[className], "globals", None) or {})
    fullGlobals.update(globalsDict)
    mod.__dict__[className].globals = fullGlobals
    if registerModule:
        sys.modules[modname] = mod
    linecache.getlines(filename, mod.__dict__)
    return mod.__dict__[className]
コード例 #15
0
from zope.security.checker import InterfaceChecker, CheckerPublic
from zope.security.metaconfigure import ClassDirective

from zope.browsermenu.menu import BrowserMenu, BrowserMenuItem, BrowserSubMenuItem
from zope.browsermenu.interfaces import IBrowserMenu, IMenuItemType
from zope.browsermenu.interfaces import IBrowserMenuItem, IBrowserSubMenuItem
from zope.browsermenu.interfaces import AddMenu


# Create special modules that contain all menu item types
from types import ModuleType as module
import sys
try:
    import zope.app
except ImportError: # we doesn't always have zope.app now
    sys.modules['zope.app'] = module('app')
menus = module('menus')
sys.modules['zope.app.menus'] = menus


_order_counter = {}


def menuDirective(_context, id=None, class_=BrowserMenu, interface=None,
                  title=u'', description=u''):
    """Registers a new browser menu."""
    if id is None and interface is None:
        raise ConfigurationError(
            "You must specify the 'id' or 'interface' attribute.")

    if interface is None:
コード例 #16
0
ファイル: metaconfigure.py プロジェクト: wpjunior/proled
from zope.app import zapi
from zope.app.component.metaconfigure import handler

# referred to through ZCML
from zope.app.publisher.browser.resourcemeta import resource
from zope.app.publisher.browser.resourcemeta import resourceDirectory
from zope.app.publisher.browser.i18nresourcemeta import I18nResource
from zope.app.publisher.browser.viewmeta import view
from zope.app.component.interface import provideInterface

# Create special modules that contain all layers and skins
from types import ModuleType as module
import sys
import zope.app

zope.app.layers = module("layers")
sys.modules["zope.app.layers"] = zope.app.layers

zope.app.skins = module("skins")
sys.modules["zope.app.skins"] = zope.app.skins


def layer(_context, name=None, interface=None, base=IBrowserRequest):
    """Provides a new layer.

    >>> class Context(object):
    ...     info = u'doc'
    ...     def __init__(self): self.actions = []
    ...     def action(self, **kw): self.actions.append(kw)

    Possibility 1: The Old Way
コード例 #17
0
ファイル: menumeta.py プロジェクト: wpjunior/proled
from zope.app.publisher.browser.menu import BrowserMenuItem, BrowserSubMenuItem
from zope.app.publisher.interfaces.browser import IBrowserMenu
from zope.app.publisher.interfaces.browser import IBrowserMenuItem
from zope.app.publisher.interfaces.browser import IMenuItemType

from zope.publisher.interfaces.browser import IBrowserRequest
from zope.app.container.interfaces import IAdding
from zope.app.component.contentdirective import ContentDirective
from zope.app.publisher.interfaces.browser import AddMenu


# Create special modules that contain all menu item types
from types import ModuleType as module
import sys

menus = module("menus")
sys.modules["zope.app.menus"] = menus


_order_counter = {}


def menuDirective(_context, id=None, class_=BrowserMenu, interface=None, title=u"", description=u""):
    """Registers a new browser menu."""
    if id is None and interface is None:
        raise ConfigurationError("You must specify the 'id' or 'interface' attribute.")

    if interface is None:
        interface = InterfaceClass(id, (), __doc__="Menu Item Type: %s" % id, __module__="zope.app.menus")
        # Add the menu item type to the `menus` module.
        # Note: We have to do this immediately, so that directives using the
コード例 #18
0
    del foo.__dict__
except TypeError:
    pass
else:
    raise TestFailed, "del foo.__dict__"

try:
    foo.__dict__ = {}
except TypeError:
    pass
else:
    raise TestFailed, "foo.__dict__ = {}"
verify(foo.__dict__ is None)

# Regularly initialized module, no docstring
foo = module("foo")
vereq(foo.__name__, "foo")
vereq(foo.__doc__, None)
vereq(foo.__dict__, {"__name__": "foo", "__doc__": None})

# ASCII docstring
foo = module("foo", "foodoc")
vereq(foo.__name__, "foo")
vereq(foo.__doc__, "foodoc")
vereq(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc"})

# Unicode docstring
foo = module("foo", u"foodoc\u1234")
vereq(foo.__name__, "foo")
vereq(foo.__doc__, u"foodoc\u1234")
vereq(foo.__dict__, {"__name__": "foo", "__doc__": u"foodoc\u1234"})
コード例 #19
0
@zope.interface.implementer(IConnection)
def connectionOfPersistent(ob):
    """An adapter which gets a ZODB connection of a persistent object.

    We are assuming the object has a parent if it has been created in
    this transaction.

    Raises ValueError if it is impossible to get a connection.
    """
    cur = ob
    while not getattr(cur, '_p_jar', None):
        cur = getattr(cur, '__parent__', None)
        if cur is None:
            return None
    return cur._p_jar


# BBB: If zope.app.keyreference is not installed, we still want
# old key references to be available. So fake a module to make
# them unpickleable.
try:
    import zope.app.keyreference
except ImportError:
    import sys
    from types import ModuleType as module
    z_a_k = module('zope.app.keyreference')
    sys.modules['zope.app.keyreference'] = z_a_k
    z_a_k_p = module('zope.app.keyreference.persistent')
    z_a_k_p.KeyReferenceToPersistent = KeyReferenceToPersistent
    sys.modules['zope.app.keyreference.persistent'] = z_a_k_p
コード例 #20
0
ファイル: persistent.py プロジェクト: grodniewicz/oship
def connectionOfPersistent(ob):
    """An adapter which gets a ZODB connection of a persistent object.

    We are assuming the object has a parent if it has been created in
    this transaction.

    Raises ValueError if it is impossible to get a connection.
    """
    cur = ob
    while not getattr(cur, "_p_jar", None):
        cur = getattr(cur, "__parent__", None)
        if cur is None:
            return None
    return cur._p_jar


# BBB: If zope.app.keyreference is not installed, we still want
# old key references to be available. So fake a module to make
# them unpickleable.
try:
    import zope.app.keyreference
except ImportError:
    import sys
    from types import ModuleType as module

    z_a_k = module("zope.app.keyreference")
    sys.modules["zope.app.keyreference"] = z_a_k
    z_a_k_p = module("zope.app.keyreference.persistent")
    z_a_k_p.KeyReferenceToPersistent = KeyReferenceToPersistent
    sys.modules["zope.app.keyreference.persistent"] = z_a_k_p
コード例 #21
0
 def testNonFileModule(self):  # {{{
     """Non-file module returns False"""
     mod = module("testmod")
     self.assertFalse(isfilemodule(mod))
コード例 #22
0
ファイル: metaconfigure.py プロジェクト: vedantc98/Plone-test
from zope.security.checker import InterfaceChecker, CheckerPublic
from zope.security.metaconfigure import ClassDirective

from zope.browsermenu.menu import BrowserMenu, BrowserMenuItem, BrowserSubMenuItem
from zope.browsermenu.interfaces import IBrowserMenu, IMenuItemType
from zope.browsermenu.interfaces import IBrowserMenuItem, IBrowserSubMenuItem
from zope.browsermenu.interfaces import AddMenu
from ._compat import _u

# Create special modules that contain all menu item types
from types import ModuleType as module
import sys
try:
    import zope.app
except ImportError:  # we doesn't always have zope.app now
    sys.modules['zope.app'] = module('app')
menus = module('menus')
sys.modules['zope.app.menus'] = menus

_order_counter = {}


def menuDirective(_context,
                  id=None,
                  class_=BrowserMenu,
                  interface=None,
                  title=_u(''),
                  description=_u('')):
    """Registers a new browser menu."""
    if id is None and interface is None:
        raise ConfigurationError(
コード例 #23
0
    del foo.__dict__
except TypeError:
    pass
else:
    raise TestFailed, "del foo.__dict__"

try:
    foo.__dict__ = {}
except TypeError:
    pass
else:
    raise TestFailed, "foo.__dict__ = {}"
verify(foo.__dict__ is None)

# Regularly initialized module, no docstring
foo = module("foo")
vereq(foo.__name__, "foo")
vereq(foo.__doc__, None)
vereq(foo.__dict__, {"__name__": "foo", "__package__": None, "__doc__": None})

# ASCII docstring
foo = module("foo", "foodoc")
vereq(foo.__name__, "foo")
vereq(foo.__doc__, "foodoc")
vereq(foo.__dict__, {
    "__name__": "foo",
    "__package__": None,
    "__doc__": "foodoc"
})

# Unicode docstring
コード例 #24
0
ファイル: persistent.py プロジェクト: CGTIC/Plone_SP
@zope.interface.implementer(IConnection)
def connectionOfPersistent(ob):
    """An adapter which gets a ZODB connection of a persistent object.

    We are assuming the object has a parent if it has been created in
    this transaction.

    Raises ValueError if it is impossible to get a connection.
    """
    cur = ob
    while not getattr(cur, '_p_jar', None):
        cur = getattr(cur, '__parent__', None)
        if cur is None:
            return None
    return cur._p_jar

# BBB: If zope.app.keyreference is not installed, we still want
# old key references to be available. So fake a module to make
# them unpickleable.
try:
    import zope.app.keyreference
except ImportError:
    import sys
    from types import ModuleType as module
    z_a_k = module('zope.app.keyreference')
    sys.modules['zope.app.keyreference'] = z_a_k
    z_a_k_p = module('zope.app.keyreference.persistent')
    z_a_k_p.KeyReferenceToPersistent = KeyReferenceToPersistent
    sys.modules['zope.app.keyreference.persistent'] = z_a_k_p
コード例 #25
0
ファイル: menumeta.py プロジェクト: bendavis78/zope
from zope.app.component.contentdirective import ClassDirective
from zope.app.pagetemplate.engine import Engine
from zope.app.container.interfaces import IAdding
from zope.app.publisher.browser.menu import BrowserMenu
from zope.app.publisher.browser.menu import BrowserMenuItem, BrowserSubMenuItem
from zope.app.publisher.interfaces.browser import IBrowserMenu
from zope.app.publisher.interfaces.browser import IBrowserMenuItem
from zope.app.publisher.interfaces.browser import IBrowserSubMenuItem
from zope.app.publisher.interfaces.browser import IMenuItemType
from zope.app.publisher.interfaces.browser import AddMenu

# Create special modules that contain all menu item types
from types import ModuleType as module
import sys
menus = module('menus')
sys.modules['zope.app.menus'] = menus


_order_counter = {}


def menuDirective(_context, id=None, class_=BrowserMenu, interface=None,
                  title=u'', description=u''):
    """Registers a new browser menu."""
    if id is None and interface is None:
        raise ConfigurationError(
            "You must specify the 'id' or 'interface' attribute.")

    if interface is None:
        if id in dir(menus):