Python new 模块,module() 实例源码

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

项目:code    作者:ActiveState    | 项目源码 | 文件源码
def save_type(self, obj):
    if getattr(new, obj.__name__, None) is obj:
        # Types in 'new' module claim their module is '__builtin__' but are not actually there
        save_global_byname(self, obj, 'new', obj.__name__)
    elif obj.__module__ == '__main__':
        # Types in __main__ are saved by value

        # Make sure we have a reference to type.__new__        
        if id(type.__new__) not in self.memo:
            self.save_reduce(getattr, (type, '__new__'), obj=type.__new__)
            self.write(pickle.POP)

        # Copy dictproxy to real dict
        d = dict(obj.__dict__)
        # Clean up unpickleable descriptors added by Python
        d.pop('__dict__', None)
        d.pop('__weakref__', None)

        args = (type(obj), obj.__name__, obj.__bases__, d)
        self.save_reduce(type.__new__, args, obj=obj)
    else:
        # Fallback to default behavior: save by reference
        pickle.Pickler.save_global(self, obj)
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def test_add_invalid(self):
        mod = new.module('spam')
        self.assertRaises(TypeError, pyamf.add_type, mod)
        self.assertRaises(TypeError, pyamf.add_type, {})
        self.assertRaises(TypeError, pyamf.add_type, 'spam')
        self.assertRaises(TypeError, pyamf.add_type, u'eggs')
        self.assertRaises(TypeError, pyamf.add_type, 1)
        self.assertRaises(TypeError, pyamf.add_type, 234234L)
        self.assertRaises(TypeError, pyamf.add_type, 34.23)
        self.assertRaises(TypeError, pyamf.add_type, None)
        self.assertRaises(TypeError, pyamf.add_type, object())

        class A:
            pass

        self.assertRaises(TypeError, pyamf.add_type, A())
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def setUp(self):
        ClassCacheClearingTestCase.setUp(self)

        self.module = new.module('foo')

        self.module.Classic = self.ClassicType
        self.module.New = self.NewType
        self.module.s = 'str'
        self.module.i = 12323
        self.module.f = 345.234
        self.module.u = u'unicode'
        self.module.l = ['list', 'of', 'junk']
        self.module.d = {'foo': 'bar', 'baz': 'gak'}
        self.module.obj = object()
        self.module.mod = self.module
        self.module.lam = lambda _: None

        self.NewType.__module__ = 'foo'
        self.ClassicType.__module__ = 'foo'

        self.spam_module = Spam.__module__
        Spam.__module__ = 'foo'

        self.names = (self.module.__name__,)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _normalize_module(module, depth=2):
    """
    Return the module specified by `module`.  In particular:
      - If `module` is a module, then return module.
      - If `module` is a string, then import and return the
        module with that name.
      - If `module` is None, then return the calling module.
        The calling module is assumed to be the module of
        the stack frame at the given depth in the call stack.
    """
    if inspect.ismodule(module):
        return module
    elif isinstance(module, (str, unicode)):
        return __import__(module, globals(), locals(), ["*"])
    elif module is None:
        return sys.modules[sys._getframe(depth).f_globals['__name__']]
    else:
        raise TypeError("Expected a module, string, or None")
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            # Some jython classes don't set __module__
            return module.__name__ == getattr(object, '__module__', None)
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, mod=None, globs=None, verbose=None,
                 isprivate=None, optionflags=0):

        warnings.warn("class Tester is deprecated; "
                      "use class doctest.DocTestRunner instead",
                      DeprecationWarning, stacklevel=2)
        if mod is None and globs is None:
            raise TypeError("Tester.__init__: must specify mod or globs")
        if mod is not None and not inspect.ismodule(mod):
            raise TypeError("Tester.__init__: mod must be a module; %r" %
                            (mod,))
        if globs is None:
            globs = mod.__dict__
        self.globs = globs

        self.verbose = verbose
        self.isprivate = isprivate
        self.optionflags = optionflags
        self.testfinder = DocTestFinder(_namefilter=isprivate)
        self.testrunner = DocTestRunner(verbose=verbose,
                                        optionflags=optionflags)
项目:SameKeyProxy    作者:xzhou    | 项目源码 | 文件源码
def _remoteInvocationMobileCode(self, method, flags, *args):
        # special trimmed-down version for mobile code methods (no locking etc)
        body=pickle.dumps((self.URI.objectID,method,flags,args),Pyro.config.PYRO_PICKLE_FORMAT)
        sock_sendmsg(self.conn.sock, self.createMsg(body), self.timeout)
        ver,answer,pflags = self.receiveMsg(self.conn,1)
        if answer is None:
            raise ProtocolError('incorrect answer received')
        answer=pickle.loads(answer)
        if isinstance(answer,PyroExceptionCapsule):
            if isinstance(answer.excObj,_InternalNoModuleError):
                # server couldn't load module, supply it
                return self.processMissingModuleError(answer.excObj, method, flags, args)
            else:
                # we have an encapsulated exception, raise it again.
                answer.raiseEx()
        return answer
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def _normalize_module(module, depth=2):
    """
    Return the module specified by `module`.  In particular:
      - If `module` is a module, then return module.
      - If `module` is a string, then import and return the
        module with that name.
      - If `module` is None, then return the calling module.
        The calling module is assumed to be the module of
        the stack frame at the given depth in the call stack.
    """
    if inspect.ismodule(module):
        return module
    elif isinstance(module, (str, unicode)):
        return __import__(module, globals(), locals(), ["*"])
    elif module is None:
        return sys.modules[sys._getframe(depth).f_globals['__name__']]
    else:
        raise TypeError("Expected a module, string, or None")
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def _from_module(self, module, object):
        """
        Return true if the given object is defined in the given
        module.
        """
        if module is None:
            return True
        elif inspect.isfunction(object):
            return module.__dict__ is object.func_globals
        elif inspect.isclass(object):
            # Some jython classes don't set __module__
            return module.__name__ == getattr(object, '__module__', None)
        elif inspect.getmodule(object) is not None:
            return module is inspect.getmodule(object)
        elif hasattr(object, '__module__'):
            return module.__name__ == object.__module__
        elif isinstance(object, property):
            return True # [XX] no way not be sure.
        else:
            raise ValueError("object must be a class or function")
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def __init__(self, mod=None, globs=None, verbose=None,
                 isprivate=None, optionflags=0):

        warnings.warn("class Tester is deprecated; "
                      "use class doctest.DocTestRunner instead",
                      DeprecationWarning, stacklevel=2)
        if mod is None and globs is None:
            raise TypeError("Tester.__init__: must specify mod or globs")
        if mod is not None and not inspect.ismodule(mod):
            raise TypeError("Tester.__init__: mod must be a module; %r" %
                            (mod,))
        if globs is None:
            globs = mod.__dict__
        self.globs = globs

        self.verbose = verbose
        self.isprivate = isprivate
        self.optionflags = optionflags
        self.testfinder = DocTestFinder(_namefilter=isprivate)
        self.testrunner = DocTestRunner(verbose=verbose,
                                        optionflags=optionflags)
项目:gyp    作者:electron    | 项目源码 | 文件源码
def _caller(tblist, skip):
    string = ""
    arr = []
    for file, line, name, text in tblist:
        if file[-10:] == "TestCmd.py":
                break
        arr = [(file, line, name, text)] + arr
    atfrom = "at"
    for file, line, name, text in arr[skip:]:
        if name in ("?", "<module>"):
            name = ""
        else:
            name = " (" + name + ")"
        string = string + ("%s line %d of %s%s\n" % (atfrom, line, file, name))
        atfrom = "\tfrom"
    return string
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def build(self, key, name, opened, entry):
        try:
            module = new.module(re_not_word.sub('_',key))
            module.__file__ = key
            exec opened in module.__dict__
            return module
        finally:
            opened.close()
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def build(self, key, name, opened, entry):
        try:
            module = new.module(re_not_word.sub('_',key))
            module.__file__ = key
            text = opened.read().replace('\r\n', '\n')
            code = compile(text, name, 'exec')
            exec code in module.__dict__
            return module
        finally:
            opened.close()
项目:v2ex-tornado-2    作者:coderyy    | 项目源码 | 文件源码
def getETreeModule(ElementTreeImplementation):
    name = "_" + ElementTreeImplementation.__name__+"builder"
    if name in moduleCache:
        return moduleCache[name]
    else:
        mod = ModuleType("_" + ElementTreeImplementation.__name__+"builder")
        objs = getETreeBuilder(ElementTreeImplementation)
        mod.__dict__.update(objs)
        moduleCache[name] = mod
        return mod
项目:v2ex-tornado-2    作者:coderyy    | 项目源码 | 文件源码
def getETreeModule(ElementTreeImplementation, fullTree=False):
    name = "_" + ElementTreeImplementation.__name__+"builder"
    if name in moduleCache:
        return moduleCache[name]
    else:
        mod = ModuleType("_" + ElementTreeImplementation.__name__+"builder")
        objs = getETreeBuilder(ElementTreeImplementation, fullTree)
        mod.__dict__.update(objs)
        moduleCache[name] = mod    
        return mod
项目:v2ex-tornado-2    作者:coderyy    | 项目源码 | 文件源码
def getDomModule(DomImplementation):
    name = "_" + DomImplementation.__name__+"builder"
    if name in moduleCache:
        return moduleCache[name]
    else:
        mod = ModuleType(name)
        objs = getDomBuilder(DomImplementation)
        mod.__dict__.update(objs)
        moduleCache[name] = mod    
        return mod
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def tearDown(self):
        ClassCacheClearingTestCase.tearDown(self)

        Spam.__module__ = self.spam_module

        self.module.__name__ = self.names
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def test_module(self):
        r = pyamf.register_package(self.module, 'com.example')
        self.check_module(r, 'com.example.')
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def test_all(self):
        self.module.Spam = Spam

        self.module.__all__ = ['Classic', 'New']

        r = pyamf.register_package(self.module, 'com.example')
        self.check_module(r, 'com.example.')
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def test_separator(self):
        r = pyamf.register_package(self.module, 'com.example', separator='/')

        self.ClassicType.__module__ = 'com.example'
        self.NewType.__module__ = 'com.example'
        self.check_module(r, 'com.example/')
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def test_name(self):
        self.module.__name__ = 'spam.eggs'
        self.ClassicType.__module__ = 'spam.eggs'
        self.NewType.__module__ = 'spam.eggs'

        r = pyamf.register_package(self.module)
        self.check_module(r, 'spam.eggs.')
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def test_strict(self):
        self.module.Spam = Spam

        Spam.__module__ = self.spam_module

        r = pyamf.register_package(self.module, 'com.example', strict=True)
        self.check_module(r, 'com.example.')
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def test_not_strict(self):
        self.module.Spam = Spam

        Spam.__module__ = self.spam_module

        r = pyamf.register_package(self.module, 'com.example', strict=False)

        self.assertEqual(len(r), 3)

        for c in [self.NewType, self.ClassicType, Spam]:
            alias = r[c]

            self.assertTrue(isinstance(alias, pyamf.ClassAlias))
            self.assertEqual(alias.klass, c)
            self.assertEqual(alias.alias, 'com.example.' + c.__name__)
项目:Tinychat-Bot--Discontinued    作者:Tinychat    | 项目源码 | 文件源码
def setUp(self):
        BaseTestCase.setUp(self)

        import new

        self.mod_name = '%s.%s' % (__name__, 'settings')
        self.settings = sys.modules[self.mod_name] = new.module(self.mod_name)

        self.old_env = os.environ.get('DJANGO_SETTINGS_MODULE', None)

        os.environ['DJANGO_SETTINGS_MODULE'] = self.mod_name

        self.settings.SECRET_KEY = 'unittest'
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def getcurrent(clazz):
    assert type(clazz) == types.ClassType, 'must be a class...'
    module = namedModule(clazz.__module__)
    currclass = getattr(module, clazz.__name__, None)
    if currclass is None:
        return clazz
    return currclass
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def namedModule(name):
    """Return a module given its name."""
    topLevel = __import__(name)
    packages = name.split(".")[1:]
    m = topLevel
    for p in packages:
        m = getattr(m, p)
    return m
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def namedObject(name):
    """Get a fully named module-global object.
    """
    classSplit = string.split(name, '.')
    module = namedModule(string.join(classSplit[:-1], '.'))
    return getattr(module, classSplit[-1])
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def namedAny(name):
    """Get a fully named package, module, module-global object, or attribute.
    """
    names = name.split('.')
    topLevelPackage = None
    moduleNames = names[:]
    while not topLevelPackage:
        try:
            trialname = '.'.join(moduleNames)
            topLevelPackage = __import__(trialname)
        except ImportError:
            # if the ImportError happened in the module being imported,
            # this is a failure that should be handed to our caller.
            # count stack frames to tell the difference.
            exc_info = sys.exc_info()
            if len(traceback.extract_tb(exc_info[2])) > 1:
                try:
                    # Clean up garbage left in sys.modules.
                    del sys.modules[trialname]
                except KeyError:
                    # Python 2.4 has fixed this.  Yay!
                    pass
                raise exc_info[0], exc_info[1], exc_info[2]
            moduleNames.pop()

    obj = topLevelPackage
    for n in names[1:]:
        obj = getattr(obj, n)

    return obj
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def macro(name, filename, source, **identifiers):
    """macro(name, source, **identifiers)

    This allows you to create macro-like behaviors in python.  See
    twisted.python.hook for an example of its usage.
    """
    if not identifiers.has_key('name'):
        identifiers['name'] = name
    source = source % identifiers
    codeplace = "<%s (macro)>" % filename
    code = compile(source, codeplace, 'exec')

    # shield your eyes!
    sm = sys.modules
    tprm = "twisted.python.reflect.macros"
    if not sm.has_key(tprm):
        macros = new.module(tprm)
        sm[tprm] = macros
        macros.count = 0
    macros = sm[tprm]
    macros.count += 1
    macroname = 'macro_' + str(macros.count)
    tprmm = tprm + '.' + macroname
    mymod = new.module(tprmm)
    sys.modules[tprmm] = mymod
    setattr(macros, macroname, mymod)
    dict = mymod.__dict__

    # Before we go on, I guess I should explain why I just did that.  Basically
    # it's a gross hack to get epydoc to work right, but the general idea is
    # that it will be a useful aid in debugging in _any_ app which expects
    # sys.modules to have the same globals as some function.  For example, it
    # would be useful if you were foolishly trying to pickle a wrapped function
    # directly from a class that had been hooked.

    exec code in dict, dict
    return dict[name]
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def testRebuild(self):
        """Rebuilding an unchanged module."""
        # This test would actually pass if rebuild was a no-op, but it
        # ensures rebuild doesn't break stuff while being a less
        # complex test than testFileRebuild.

        x = crash_test_dummy.X('a')

        rebuild.rebuild(crash_test_dummy, doLog=False)
        # Instance rebuilding is triggered by attribute access.
        x.do()
        self.failUnlessIdentical(x.__class__, crash_test_dummy.X)

        self.failUnlessIdentical(f, crash_test_dummy.foo)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def setUp(self):
        self.m = new.module('whipping')
        sys.modules['whipping'] = self.m
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _module_relative_path(module, path):
    if not inspect.ismodule(module):
        raise TypeError, 'Expected a module: %r' % module
    if path.startswith('/'):
        raise ValueError, 'Module-relative files may not have absolute paths'

    # Find the base directory for the path.
    if hasattr(module, '__file__'):
        # A normal module/package
        basedir = os.path.split(module.__file__)[0]
    elif module.__name__ == '__main__':
        # An interactive session.
        if len(sys.argv)>0 and sys.argv[0] != '':
            basedir = os.path.split(sys.argv[0])[0]
        else:
            basedir = os.curdir
    else:
        # A module w/o __file__ (this includes builtins)
        raise ValueError("Can't resolve paths relative to the module " +
                         module + " (it has no __file__)")

    # Combine the base directory and the path.
    return os.path.join(basedir, *(path.split('/')))

######################################################################
## 2. Example & DocTest
######################################################################
## - An "example" is a <source, want> pair, where "source" is a
##   fragment of source code, and "want" is the expected output for
##   "source."  The Example class also includes information about
##   where the example was extracted from.
##
## - A "doctest" is a collection of examples, typically extracted from
##   a string (such as an object's docstring).  The DocTest class also
##   includes information about where the string was extracted from.
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def run_docstring_examples(f, globs, verbose=False, name="NoName",
                           compileflags=None, optionflags=0):
    """
    Test examples in the given object's docstring (`f`), using `globs`
    as globals.  Optional argument `name` is used in failure messages.
    If the optional argument `verbose` is true, then generate output
    even if there are no failures.

    `compileflags` gives the set of flags that should be used by the
    Python compiler when running the examples.  If not specified, then
    it will default to the set of future-import flags that apply to
    `globs`.

    Optional keyword arg `optionflags` specifies options for the
    testing and output.  See the documentation for `testmod` for more
    information.
    """
    # Find, parse, and run all tests in the given module.
    finder = DocTestFinder(verbose=verbose, recurse=False)
    runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
    for test in finder.find(f, name, globs=globs):
        runner.run(test, compileflags=compileflags)

######################################################################
## 7. Tester
######################################################################
# This is provided only for backwards compatibility.  It's not
# actually used in any way.
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def rundoc(self, object, name=None, module=None):
        f = t = 0
        tests = self.testfinder.find(object, name, module=module,
                                     globs=self.globs)
        for test in tests:
            (f2, t2) = self.testrunner.run(test)
            (f,t) = (f+f2, t+t2)
        return (f,t)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def rundict(self, d, name, module=None):
        import new
        m = new.module(name)
        m.__dict__.update(d)
        if module is None:
            module = False
        return self.rundoc(m, name, module)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def run__test__(self, d, name):
        import new
        m = new.module(name)
        m.__test__ = d
        return self.rundoc(m, name)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def testsource(module, name):
    """Extract the test sources from a doctest docstring as a script.

    Provide the module (or dotted name of the module) containing the
    test to be debugged and the name (within the module) of the object
    with the doc string with tests to be debugged.
    """
    module = _normalize_module(module)
    tests = DocTestFinder().find(module)
    test = [t for t in tests if t.name == name]
    if not test:
        raise ValueError(name, "not found in tests")
    test = test[0]
    testsrc = script_from_examples(test.docstring)
    return testsrc
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def debug(module, name, pm=False):
    """Debug a single doctest docstring.

    Provide the module (or dotted name of the module) containing the
    test to be debugged and the name (within the module) of the object
    with the docstring with tests to be debugged.
    """
    module = _normalize_module(module)
    testsrc = testsource(module, name)
    debug_script(testsrc, pm, module.__dict__)
项目:SameKeyProxy    作者:xzhou    | 项目源码 | 文件源码
def remote_retrieve_code(self, name):
        # XXX codeValidator: can we somehow get the client's address it is sent to?
        # XXX this code is ugly. And duplicated in protocol.py remoteInvocation.
        if Pyro.config.PYRO_MOBILE_CODE and self.codeValidator(name,None,None):
            Log.msg("ObjBase","supplying code: ",name)
            try:
                importmodule=new.module("pyro-server-import")
                try:
                    exec "import " + name in importmodule.__dict__
                except ImportError:
                    Log.error("ObjBase","Client wanted a non-existing module:", name)
                    raise PyroError("Client wanted a non-existing module", name)
                m=eval("importmodule."+name)
                # try to load the module's compiled source, or the real .py source if that fails.
                # note that the source code (.py) is opened with universal newline mode
                (filebase,ext)=os.path.splitext(m.__file__)
                if ext.startswith(".PY"):
                    exts = ( (".PYO","rb"), (".PYC","rb"), (".PY","rU") )   # uppercase
                else:
                    exts = ( (".pyo","rb"), (".pyc","rb"), (".py","rU") )   # lowercase
                for ext,mode in exts:
                    try:
                        m=open(filebase+ext, mode).read()
                        return m  # supply the module to the client!
                    except:
                        pass
                Log.error("ObjBase","cannot read module source code for module:", name)
                raise PyroError("cannot read module source code")
            finally:
                del importmodule
        else:
            Log.error("ObjBase","attempt to retrieve code denied:", name)
            raise PyroError("attempt to retrieve code denied")
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def getcurrent(clazz):
    assert type(clazz) == types.ClassType, 'must be a class...'
    module = namedModule(clazz.__module__)
    currclass = getattr(module, clazz.__name__, None)
    if currclass is None:
        return clazz
    return currclass
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def namedModule(name):
    """Return a module given its name."""
    topLevel = __import__(name)
    packages = name.split(".")[1:]
    m = topLevel
    for p in packages:
        m = getattr(m, p)
    return m
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def namedObject(name):
    """Get a fully named module-global object.
    """
    classSplit = string.split(name, '.')
    module = namedModule(string.join(classSplit[:-1], '.'))
    return getattr(module, classSplit[-1])
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def namedAny(name):
    """Get a fully named package, module, module-global object, or attribute.
    """
    names = name.split('.')
    topLevelPackage = None
    moduleNames = names[:]
    while not topLevelPackage:
        try:
            trialname = '.'.join(moduleNames)
            topLevelPackage = __import__(trialname)
        except ImportError:
            # if the ImportError happened in the module being imported,
            # this is a failure that should be handed to our caller.
            # count stack frames to tell the difference.
            exc_info = sys.exc_info()
            if len(traceback.extract_tb(exc_info[2])) > 1:
                try:
                    # Clean up garbage left in sys.modules.
                    del sys.modules[trialname]
                except KeyError:
                    # Python 2.4 has fixed this.  Yay!
                    pass
                raise exc_info[0], exc_info[1], exc_info[2]
            moduleNames.pop()

    obj = topLevelPackage
    for n in names[1:]:
        obj = getattr(obj, n)

    return obj
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def macro(name, filename, source, **identifiers):
    """macro(name, source, **identifiers)

    This allows you to create macro-like behaviors in python.  See
    twisted.python.hook for an example of its usage.
    """
    if not identifiers.has_key('name'):
        identifiers['name'] = name
    source = source % identifiers
    codeplace = "<%s (macro)>" % filename
    code = compile(source, codeplace, 'exec')

    # shield your eyes!
    sm = sys.modules
    tprm = "twisted.python.reflect.macros"
    if not sm.has_key(tprm):
        macros = new.module(tprm)
        sm[tprm] = macros
        macros.count = 0
    macros = sm[tprm]
    macros.count += 1
    macroname = 'macro_' + str(macros.count)
    tprmm = tprm + '.' + macroname
    mymod = new.module(tprmm)
    sys.modules[tprmm] = mymod
    setattr(macros, macroname, mymod)
    dict = mymod.__dict__

    # Before we go on, I guess I should explain why I just did that.  Basically
    # it's a gross hack to get epydoc to work right, but the general idea is
    # that it will be a useful aid in debugging in _any_ app which expects
    # sys.modules to have the same globals as some function.  For example, it
    # would be useful if you were foolishly trying to pickle a wrapped function
    # directly from a class that had been hooked.

    exec code in dict, dict
    return dict[name]
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def testRebuild(self):
        """Rebuilding an unchanged module."""
        # This test would actually pass if rebuild was a no-op, but it
        # ensures rebuild doesn't break stuff while being a less
        # complex test than testFileRebuild.

        x = crash_test_dummy.X('a')

        rebuild.rebuild(crash_test_dummy, doLog=False)
        # Instance rebuilding is triggered by attribute access.
        x.do()
        self.failUnlessIdentical(x.__class__, crash_test_dummy.X)

        self.failUnlessIdentical(f, crash_test_dummy.foo)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def setUp(self):
        self.m = new.module('whipping')
        sys.modules['whipping'] = self.m
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def _module_relative_path(module, path):
    if not inspect.ismodule(module):
        raise TypeError, 'Expected a module: %r' % module
    if path.startswith('/'):
        raise ValueError, 'Module-relative files may not have absolute paths'

    # Find the base directory for the path.
    if hasattr(module, '__file__'):
        # A normal module/package
        basedir = os.path.split(module.__file__)[0]
    elif module.__name__ == '__main__':
        # An interactive session.
        if len(sys.argv)>0 and sys.argv[0] != '':
            basedir = os.path.split(sys.argv[0])[0]
        else:
            basedir = os.curdir
    else:
        # A module w/o __file__ (this includes builtins)
        raise ValueError("Can't resolve paths relative to the module " +
                         module + " (it has no __file__)")

    # Combine the base directory and the path.
    return os.path.join(basedir, *(path.split('/')))

######################################################################
## 2. Example & DocTest
######################################################################
## - An "example" is a <source, want> pair, where "source" is a
##   fragment of source code, and "want" is the expected output for
##   "source."  The Example class also includes information about
##   where the example was extracted from.
##
## - A "doctest" is a collection of examples, typically extracted from
##   a string (such as an object's docstring).  The DocTest class also
##   includes information about where the string was extracted from.
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def run_docstring_examples(f, globs, verbose=False, name="NoName",
                           compileflags=None, optionflags=0):
    """
    Test examples in the given object's docstring (`f`), using `globs`
    as globals.  Optional argument `name` is used in failure messages.
    If the optional argument `verbose` is true, then generate output
    even if there are no failures.

    `compileflags` gives the set of flags that should be used by the
    Python compiler when running the examples.  If not specified, then
    it will default to the set of future-import flags that apply to
    `globs`.

    Optional keyword arg `optionflags` specifies options for the
    testing and output.  See the documentation for `testmod` for more
    information.
    """
    # Find, parse, and run all tests in the given module.
    finder = DocTestFinder(verbose=verbose, recurse=False)
    runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
    for test in finder.find(f, name, globs=globs):
        runner.run(test, compileflags=compileflags)

######################################################################
## 7. Tester
######################################################################
# This is provided only for backwards compatibility.  It's not
# actually used in any way.
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def rundoc(self, object, name=None, module=None):
        f = t = 0
        tests = self.testfinder.find(object, name, module=module,
                                     globs=self.globs)
        for test in tests:
            (f2, t2) = self.testrunner.run(test)
            (f,t) = (f+f2, t+t2)
        return (f,t)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def rundict(self, d, name, module=None):
        import new
        m = new.module(name)
        m.__dict__.update(d)
        if module is None:
            module = False
        return self.rundoc(m, name, module)