コード例 #1
0
    def privmsg(self, user, channel, msg):
        """Handles user messages from channels

        This hooks every privmsg sent to the channel and sends the commands off
        to cmds.dispatch to process, then replies to the channel accordingly.

        The @reload command needs to be handled here though, as it allows edits
        to be made to trailbot without disconnecting from IRC. It should get a
        list from cmds.dispatch if it needs to pm someone, otherwise it gets a
        string back and msgs the channel.

        """
        user = user.split('!', 1)[0]

        if msg == '%reload':
            rebuild.rebuild(cmds)
            rebuild.rebuild(voice)
            self.msg(channel, 'reloaded and ready to go')
        else:
            reply = cmds.dispatch(user, msg)

            if type(reply) is types.StringType:
                self.msg(channel, reply)
            else:
                if len(reply):
                    self.msg(channel, reply[0])
                    for trip in reply[1:]:
                        self.msg(user, trip)
コード例 #2
0
ファイル: jobs.py プロジェクト: D3f0/txscada
    def remote_registerClasses(self, *args):
        """
        Instructs my broker to register the classes specified by the
        argument(s).

        The classes will be registered for B{all} jobs, and are specified by
        their string representations::
        
            <package(s).module.class>
        
        """
        modules = []
        for stringRep in args:
            # Load the class for the string representation
            cls = reflect.namedObject(stringRep)
            # Register instances of the class, including its type and module
            pb.setUnjellyableForClass(stringRep, cls)
            if cls.__module__ not in modules:
                modules.append(cls.__module__)
        # Try to build the modules for the classes in case they've changed
        # since the last run
        for module in modules:
            try:
                rebuild(reflect.namedModule(module), doLog=False)
            except:
                pass
コード例 #3
0
    def test_FileRebuild(self):
        from twisted.python.util import sibpath
        import shutil, time

        shutil.copyfile(
            sibpath(__file__, "myrebuilder1.py"),
            os.path.join(self.fakelibPath, "myrebuilder.py"),
        )
        from twisted_rebuild_fakelib import myrebuilder  # type: ignore[import]

        a = myrebuilder.A()
        b = myrebuilder.B()
        i = myrebuilder.Inherit()
        self.assertEqual(a.a(), "a")
        # Necessary because the file has not "changed" if a second has not gone
        # by in unix.  This sucks, but it's not often that you'll be doing more
        # than one reload per second.
        time.sleep(1.1)
        shutil.copyfile(
            sibpath(__file__, "myrebuilder2.py"),
            os.path.join(self.fakelibPath, "myrebuilder.py"),
        )
        rebuild.rebuild(myrebuilder)
        b2 = myrebuilder.B()
        self.assertEqual(b2.b(), "c")
        self.assertEqual(b.b(), "c")
        self.assertEqual(i.a(), "d")
        self.assertEqual(a.a(), "b")
コード例 #4
0
ファイル: module.py プロジェクト: cypreess/mamba
    def reload(self, module):
        """Reload a controller module

        :param module: the module to reload
        :type module: str
        """

        module_store = self.lookup(module)
        object = module_store.get('object')
        tmp_module = module_store.get('module')
        if object is None or object.loaded is False:
            raise ModuleError('Tried to reload %s that is not yet loaded' %
                              module)

        log.msg('{}: {} {}'.format(output.green('Reloading module'),
                                   object.__class__.__name__, object))

        try:
            rebuild.rebuild(tmp_module, False)
        except Exception as error:
            log.msg('{}: {}\n{}'.format(output.brown('Error reloading module'),
                                        error,
                                        traceback.format_exc()[:-1]))
        finally:
            object_name = object.__class__.__name__
            del self._modules[module]['object']
            gc.collect()
            temp_object = getattr(tmp_module, object_name)()
            temp_object.loaded = True
            self._modules[module]['object'] = temp_object
コード例 #5
0
 def loadModule(self, name):
     for module in getPlugins(IBotModule, heufybot.modules):
         if module.name and module.name.lower() == name.lower():
             rebuild(importlib.import_module(module.__module__))
             self._loadModuleData(module)
             return module.name
     raise ModuleLoaderError(name, "The module could not be found.", ModuleLoadType.LOAD)
コード例 #6
0
    def on_modified(self, event):
        handlerModuleDetails = evaluateHandlerFileEvent(event)

        if not handlerModuleDetails:
            return

        handlerModulePath, handlerModule = handlerModuleDetails

        if handlerModule not in sys.modules:
            return False

        self.logger.info("Reloading %s", handlerModule)

        xtHandlersCollection, xmlHandlersCollection = removeHandlersByModule(
            handlerModulePath)

        handlerModuleObject = sys.modules[handlerModule]

        try:
            rebuild.rebuild(handlerModuleObject)

            self.logger.info("Successfully reloaded %s!", handlerModule)

        except Exception as rebuildError:
            self.logger.error("%s detected in %s, not reloading.",
                              rebuildError.__class__.__name__, handlerModule)
            self.logger.info("Restoring handler references...")

            Handlers.XTHandlers = xtHandlersCollection
            Handlers.XMLHandlers = xmlHandlersCollection

            self.logger.info("Handler references restored. Phew!")
コード例 #7
0
    def testRebuildInteraction(self):
        from twisted.persisted import dirdbm
        from twisted.python import rebuild

        s = dirdbm.Shelf('dirdbm.rebuild.test')
        s['key'] = 'value'
        rebuild.rebuild(dirdbm)
コード例 #8
0
ファイル: sioclogbot.py プロジェクト: tuukka/sioclog
    def irc_PRIVMSG(self, line):
        msg = line.args[1]

        if line.args[0].startswith("#"):
            if msg[1:].startswith(self.nick):
                if msg[1+len(self.nick)+1:].strip() == "pointer":
                    answerURI = self.factory.rootURI + line.args[0][1:].lower() + '/' + line.ztime.rstrip("Z").replace("T", "#")
                    answer = "That line is " + answerURI
                    self.sendLine(Line("NOTICE", [line.args[0], answer]))

        if line.args[0] != self.nick:
            return False # not to us
        if parseprefix(line.prefix)[0] != self.factory.admin:
            return False # not from admin

        if msg == "+rebuild":
            try:
                rebuild(sioclogbot)
                info("rebuilt")
            except:
                print_exc()
        elif msg.startswith("+do "):
            try:
                self.sendLine(Line(linestr=msg[len("+do "):]))
            except:
                print_exc()

        return False # log
コード例 #9
0
ファイル: test_dirdbm.py プロジェクト: ssilverek/kodb
    def testRebuildInteraction(self):
        from twisted.persisted import dirdbm
        from twisted.python import rebuild

        s = dirdbm.Shelf("dirdbm.rebuild.test")
        s["key"] = "value"
        rebuild.rebuild(dirdbm)
コード例 #10
0
    def remote_registerClasses(self, *args):
        """
        Instructs my broker to register the classes specified by the
        argument(s).

        The classes will be registered for B{all} jobs, and are specified by
        their string representations::
        
            <package(s).module.class>
        
        """
        modules = []
        for stringRep in args:
            # Load the class for the string representation
            cls = reflect.namedObject(stringRep)
            # Register instances of the class, including its type and module
            pb.setUnjellyableForClass(stringRep, cls)
            if cls.__module__ not in modules:
                modules.append(cls.__module__)
        # Try to build the modules for the classes in case they've changed
        # since the last run
        for module in modules:
            try:
                rebuild(reflect.namedModule(module), doLog=False)
            except:
                pass
コード例 #11
0
 def testRebuild(self):
     """Rebuilding an unchanged module."""
     x = crash_test_dummy.X('a')
     rebuild.rebuild(crash_test_dummy, doLog=False)
     x.do()
     self.failUnlessIdentical(x.__class__, crash_test_dummy.X)
     self.failUnlessIdentical(f, crash_test_dummy.foo)
コード例 #12
0
ファイル: test_dirdbm.py プロジェクト: Almad/twisted
    def testRebuildInteraction(self):
        from twisted.persisted import dirdbm
        from twisted.python import rebuild

        s = dirdbm.Shelf('dirdbm.rebuild.test')
        s['key'] = 'value'
        rebuild.rebuild(dirdbm)
コード例 #13
0
 def loadModule(self, name):
     for module in getPlugins(IBotModule, heufybot.modules):
         if module.name and module.name.lower() == name.lower():
             rebuild(importlib.import_module(module.__module__))
             self._loadModuleData(module)
             return module.name
     raise ModuleLoaderError(name, "The module could not be found.",
                             ModuleLoadType.LOAD)
コード例 #14
0
ファイル: widgets.py プロジェクト: duyMinhCSE/eXe_handmake
 def reload(self, request):
     request.redirect("..")
     x = []
     write = x.append
     for module in self.modules:
         rebuild.rebuild(module)
         write('<li>reloaded %s<br />' % module.__name__)
     return x
コード例 #15
0
ファイル: modulehandler.py プロジェクト: HubbeKing/PyHeufyBot
 def loadModule(self, name):
     for module in getPlugins(IBotModule, heufybot.modules):
         if not module.name:
             raise ModuleLoaderError("???", "Module did not provide a name")
         if module.name == name:
             rebuild(importlib.import_module(module.__module__))
             self._loadModuleData(module)
             break
コード例 #16
0
    def loadModule(self, name):
        for module in getPlugins(IModule, pymoronbot.modules):
            if module.__class__.__name__ and module.__class__.__name__.lower() == name.lower():
                rebuild(importlib.import_module(module.__module__))
                self._loadModuleData(module)

                print('-- {} loaded'.format(module.__class__.__name__))

                return module.__class__.__name__
コード例 #17
0
ファイル: widgets.py プロジェクト: lhl/songclub
 def reload(self, request):
     request.setHeader("location", "..")
     request.setResponseCode(http.MOVED_PERMANENTLY)
     x = []
     write = x.append
     for module in self.modules:
         rebuild.rebuild(module)
         write('<li>reloaded %s<br>' % module.__name__)
     return x
コード例 #18
0
ファイル: botbot.py プロジェクト: fxia22/ASM_xf
 def bot_rebuild(self, sender, message, metadata):
     self.loadBotList()
     from twisted.words import botbot
     from twisted.python.rebuild import rebuild
     from twisted.python.reflect import namedModule
     if message:
         rebuild(namedModule(message))
     else:
         rebuild(botbot)
コード例 #19
0
ファイル: widgets.py プロジェクト: katrinleinweber/songclub
 def reload(self, request):
     request.setHeader("location", "..")
     request.setResponseCode(http.MOVED_PERMANENTLY)
     x = []
     write = x.append
     for module in self.modules:
         rebuild.rebuild(module)
         write('<li>reloaded %s<br>' % module.__name__)
     return x
コード例 #20
0
ファイル: commands.py プロジェクト: NoviarRS/PSO2Proxy-PSO2
 def call_from_console(self):
     if len(self.args.split(' ')) < 2:
         return "[Command] Invalid usage. (Usage: reloadplugin <Plugin Name>)"
     modulearg = self.args.split(' ')[1]
     if modulearg not in sys.modules.keys():
         return "That plugin (%s) is not loaded." % modulearg
     output = "[ShipProxy] Reloading plugin: %s..." % modulearg
     rebuild.rebuild(sys.modules[modulearg])
     output += "[ShipProxy] Plugin reloaded!\n"
     return output
コード例 #21
0
ファイル: commands.py プロジェクト: Daikui/PSO2Proxy
 def call_from_console(self):
     if len(self.args.split(' ')) < 2:
         return "[Command] Invalid usage. (Usage: reloadplugin <Plugin Name>)"
     modulearg = self.args.split(' ')[1]
     if modulearg not in sys.modules.keys():
         return "That plugin (%s) is not loaded." % modulearg
     output = "[ShipProxy] Reloading plugin: %s..." % modulearg
     rebuild.rebuild(sys.modules[modulearg])
     output += "[ShipProxy] Plugin reloaded!\n"
     return output
コード例 #22
0
ファイル: modulehandler.py プロジェクト: DesertBot/DesertBot
    def loadModule(self, name: str, rebuild_: bool=True) -> str:
        for module in getPlugins(IModule, desertbot.modules):
            if module.__class__.__name__ and module.__class__.__name__.lower() == name.lower():
                if rebuild_:
                    rebuild(importlib.import_module(module.__module__))
                self._loadModuleData(module)

                self.logger.info('Module {} loaded'.format(module.__class__.__name__))

                return module.__class__.__name__
コード例 #23
0
ファイル: console.py プロジェクト: serpent-project/serpent
 def do_reload(self, *modules):
     """ try to reload one or more python modules.
         KNOW WHAT YOU ARE DOING!
     """
     self.sendLine("reloading module(s) %s" % ", ".join(modules))
     for m in modules:
         try:
             m_ = import_module(m)
             rebuild.rebuild(m_)
         except Exception, e:
             self.sendLine("reloading module %s threw Exception %s" % (m, e))
コード例 #24
0
ファイル: Modules.py プロジェクト: shaunidiot/Timeline
 def reloadModules(self, name=None):
     for i in range(len(self.modules)):
         try:
             if name == None:
                 self.modules[i] = rebuild(self.modules[i])
             elif self.modules[i].__name__ == name:
                 self.modules[i] = rebuild(self.modules[i])
         except Exception, e:
             self.logger.error("Error rebuilding - {0}".format(
                 self.modules[i].__name__))
             self.logger.error("[TE030] {0}".format(e))
コード例 #25
0
 def testComponentInteraction(self):
     x = crash_test_dummy.XComponent()
     x.setAdapter(crash_test_dummy.IX, crash_test_dummy.XA)
     oldComponent = x.getComponent(crash_test_dummy.IX)
     rebuild.rebuild(crash_test_dummy, 0)
     newComponent = x.getComponent(crash_test_dummy.IX)
     newComponent.method()
     self.assertEquals(newComponent.__class__, crash_test_dummy.XA)
     from twisted.python import components
     self.failUnlessRaises(ValueError, components.registerAdapter,
                           crash_test_dummy.XA, crash_test_dummy.X,
                           crash_test_dummy.IX)
コード例 #26
0
 def loadModule(self, name):
     for module in getPlugins(IBotModule, desertbot.modules):
         if not module.name:
             raise ModuleLoaderError("???",
                                     "Module did not provide a name.",
                                     ModuleLoadType.LOAD)
         if module.name.lower() == name.lower():
             rebuild(importlib.import_module(module.__module__))
             self._loadModuleData(module)
             return module.name
     raise ModuleLoaderError(name, "The module could not be found.",
                             ModuleLoadType.LOAD)
コード例 #27
0
ファイル: modulehandler.py プロジェクト: lunik1/DesertBot
    def loadModule(self, name: str, rebuild_: bool = True) -> str:
        for module in getPlugins(IModule, desertbot.modules):
            if module.__class__.__name__ and module.__class__.__name__.lower(
            ) == name.lower():
                if rebuild_:
                    rebuild(importlib.import_module(module.__module__))
                self._loadModuleData(module)

                self.logger.info('Module {} loaded'.format(
                    module.__class__.__name__))

                return module.__class__.__name__
コード例 #28
0
ファイル: Debug.py プロジェクト: Kays/cia-vc
def rebuildPackage(package):
    """Recursively rebuild all loaded modules in the given package"""
    rebuild.rebuild(package)
    # If this is really a package instead of a module, look for children
    try:
        f = package.__file__
    except AttributeError:
        return
    if package.__file__.find("__init__") >= 0:
        for item in package.__dict__.itervalues():
            # Is it a module?
            if type(item) == type(package):
                rebuildPackage(item)
コード例 #29
0
 def test_hashException(self):
     """
     Rebuilding something that has a __hash__ that raises a non-TypeError
     shouldn't cause rebuild to die.
     """
     global unhashableObject
     unhashableObject = HashRaisesRuntimeError()
     def _cleanup():
         global unhashableObject
         unhashableObject = None
     self.addCleanup(_cleanup)
     rebuild.rebuild(rebuild)
     self.assertEquals(unhashableObject.hashCalled, True)
コード例 #30
0
def rebuildPackage(package):
    """Recursively rebuild all loaded modules in the given package"""
    rebuild.rebuild(package)
    # If this is really a package instead of a module, look for children
    try:
        f = package.__file__
    except AttributeError:
        return
    if package.__file__.find("__init__") >= 0:
        for item in package.__dict__.itervalues():
            # Is it a module?
            if type(item) == type(package):
                rebuildPackage(item)
コード例 #31
0
ファイル: pages_base.py プロジェクト: cryptixman/tzmud
 def child_rebuild(self, ctx):
     import pages_base
     rebuild(pages_base)
     import pages_index
     rebuild(pages_index)
     import pages_rooms
     rebuild(pages_rooms)
     import pages_edit
     rebuild(pages_edit)
     import pages_exits
     rebuild(pages_exits)
     self.goback(ctx)
     return self
コード例 #32
0
 def test_hashException(self):
     """
     Rebuilding something that has a __hash__ that raises a non-TypeError
     shouldn't cause rebuild to die.
     """
     global unhashableObject
     unhashableObject = HashRaisesRuntimeError()
     def _cleanup():
         global unhashableObject
         unhashableObject = None
     self.addCleanup(_cleanup)
     rebuild.rebuild(rebuild)
     self.assertEqual(unhashableObject.hashCalled, True)
コード例 #33
0
ファイル: app.py プロジェクト: spicerack/sage
    def reload(self, name, event_src_path=None):
        """ Try to fully rebuild an app """

        # Don't reload the same app if we did it within last the 5 sec
        if time.time() - self._last_reload.get(name, 0) < 5:
            return

        self._last_reload[name] = time.time()

        if name not in self:
            return False

        if hasattr(self[name], 'pre_reload'):
            self[name].pre_reload()

        try:
            if event_src_path:

                if event_src_path.endswith('.py'):
                    path, f = os.path.split(event_src_path)
                    pyc = path + '/' + f[:-3] + '.pyc'
                    if os.path.isfile(pyc):
                        os.remove(pyc)

                targets = []

                for mname, module in sys.modules.items():
                    if module:
                        if hasattr(module, '__file__'):
                            if event_src_path in module.__file__:
                                targets.append(module)

                for target in targets:
                    rebuild(target, False)

            else:
                # generally try to reload the app
                self[name] = rebuild(self[name], False)
        except:
            sage._log.msg("Error reloading '%s'" % name)
            sage._log.err()
            return False

        gc.collect()

        if hasattr(self[name], 'post_reload'):
            self[name].post_reload()

        sage._log.msg("Reloaded app '%s'" % self.meta[name].name)

        return True
コード例 #34
0
    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)
コード例 #35
0
    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)
コード例 #36
0
    def on_modified(self, event):
        # Ignore all directory events
        if event.is_directory:
            return

        handlerModulePath = event.src_path[2:]
        handlerModule = handlerModulePath.replace("/", ".")[:-3]

        if handlerModule not in sys.modules:
            return

        self.logger.debug("Reloading %s", handlerModule)

        if "Houdini.Handlers.Play" in handlerModule:
            handlerItems = Handlers.XTHandlers.items()
            handlerCollection = copy.deepcopy(Handlers.XTHandlers)

        else:
            handlerItems = Handlers.XMLHandlers.items()
            handlerCollection = copy.deepcopy(Handlers.XMLHandlers)

        for handlerId, handlerListeners in handlerItems:
            for handlerListener in handlerListeners:
                # Look through the list of listeners to determine which need to be removed
                # self.logger.debug("Comparing %s to %s", handlerListener.functionFile, handlerModulePath)

                if handlerListener.functionFile == handlerModulePath:
                    self.logger.debug("Removing a %s listener", handlerId)
                    handlerListeners.remove(handlerListener)

        handlerModuleObject = sys.modules[handlerModule]

        try:
            rebuild.rebuild(handlerModuleObject)

        except (IndentationError, SyntaxError) as rebuildError:
            self.logger.error("%s detected in %s, not reloading.",
                              rebuildError.__class__.__name__, handlerModule)
            self.logger.info("Restoring handler references...")

            if "Houdini.Handlers.Play" in handlerModule:
                Handlers.XTHandlers = handlerCollection
            else:
                Handlers.XMLHandlers = handlerCollection

            self.logger.info("Handler references restored. Phew!")
        except:
            self.logger.error("Unable to reload %s due to an unknown reason!",
                              handlerModule)
コード例 #37
0
ファイル: service.py プロジェクト: tehasdf/txdevserver
    def check_and_reload(self, subOptions):
        modules_changed = code_changed()
        if modules_changed:
            for module in modules_changed:

                try:
                    rebuild(module)
                except Exception as e:
                    self.logger.critical("Error reloading %s: %s", module.__name__, e)
                    self.app = NoResource("There was an error reloading the app.")
                    break
                else:
                    self.logger.critical("Reloaded %s (%d modules loaded)", module.__name__, len(sys.modules))
            else:
                self.attach_app(subOptions)
コード例 #38
0
 def patch(self):
     try:
         access_token = cfg.reload_token  # Access Token
         try:
             request_token = request.get_json(force=True)['token']
         except BaseException:
             request_token = ''
         if request_token == access_token:
             rebuild.rebuild(wf)
             rebuild.rebuild(misc)
             return 'Successfully reloaded modules.', 200
         else:
             return 'Access Denied.', 403
     except Exception as e:
         return repr(e), 500
コード例 #39
0
    def privmsg(self, user, channel, message):
        print 'privmsg', user, channel, message
        username = user[:user.index('!')]
        host = user[user.rindex('@') + 1:]
        if channel.startswith('#'):
            dest = channel
        else:
            dest = username

        if message == 'rebuild':
            try:
                rebuild(darcsbot)
                print 'rebuilt'
            except:
                print_exc()
            return
コード例 #40
0
ファイル: BaneBot.py プロジェクト: Hasimir/eventsdb
    def reloadPluginModule(self, stuff, filepath, mask):
        # Get the actual filepath
        afpath = os.path.abspath(filepath.path).replace('.conf', '.py')

        # See if we need to reload a plugin, load a new plugin, or ignore
        if mask == inotify.IN_MODIFY and afpath in self.modules:
            try:
                self.modules[afpath] = rebuild(self.modules[afpath])
                self.loadPluginObject(self.modules[afpath], reloading=True)
                if self.logging:
                    log.msg('Reloaded {}'.format(filepath))
            except:
                if self.logging:
                    log.err('Failed to reload {} | {} | {}'.\
                            format( filepath
                                  , sys.exc_info()[0]
                                  , traceback.format_exc()
                                  )
                           )

        elif mask == inotify.IN_CREATE and afpath.endswith('.py'):
            plugin = afpath.split('/')[-1].rstrip('.py')
            self.modules[afpath] = import_module('plugins.{}'.format(plugin))

        else:
            return
コード例 #41
0
    def testComponentInteraction(self):
        x = crash_test_dummy.XComponent()
        x.setAdapter(crash_test_dummy.IX, crash_test_dummy.XA)
        x.getComponent(crash_test_dummy.IX)
        rebuild.rebuild(crash_test_dummy, 0)
        newComponent = x.getComponent(crash_test_dummy.IX)

        newComponent.method()

        self.assertEqual(newComponent.__class__, crash_test_dummy.XA)

        # Test that a duplicate registerAdapter is not allowed
        from twisted.python import components
        self.assertRaises(ValueError, components.registerAdapter,
                              crash_test_dummy.XA, crash_test_dummy.X,
                              crash_test_dummy.IX)
コード例 #42
0
    def reloadPluginModule(self, stuff, filepath, mask):
        # Get the actual filepath
        afpath = os.path.abspath(filepath.path).replace('.conf', '.py')

        # See if we need to reload a plugin, load a new plugin, or ignore
        if mask == inotify.IN_MODIFY and afpath in self.modules:
            try:
                self.modules[afpath] = rebuild(self.modules[afpath])
                self.loadPluginObject(self.modules[afpath], reloading=True)
                if self.logging:
                    log.msg('Reloaded {}'.format(filepath))
            except:
                if self.logging:
                    log.err('Failed to reload {} | {} | {}'.\
                            format( filepath
                                  , sys.exc_info()[0]
                                  , traceback.format_exc()
                                  )
                           )

        elif mask == inotify.IN_CREATE and afpath.endswith('.py'):
            plugin = afpath.split('/')[-1].rstrip('.py')
            self.modules[afpath] = import_module('plugins.{}'.format(plugin))

        else:
            return
コード例 #43
0
ファイル: test_rebuild.py プロジェクト: levanhong05/MeshMagic
    def testComponentInteraction(self):
        x = crash_test_dummy.XComponent()
        x.setAdapter(crash_test_dummy.IX, crash_test_dummy.XA)
        oldComponent = x.getComponent(crash_test_dummy.IX)
        rebuild.rebuild(crash_test_dummy, 0)
        newComponent = x.getComponent(crash_test_dummy.IX)

        newComponent.method()

        self.assertEqual(newComponent.__class__, crash_test_dummy.XA)

        # Test that a duplicate registerAdapter is not allowed
        from twisted.python import components
        self.failUnlessRaises(ValueError, components.registerAdapter,
                              crash_test_dummy.XA, crash_test_dummy.X,
                              crash_test_dummy.IX)
コード例 #44
0
ファイル: reload.py プロジェクト: offlinehacker/flumotion
def reloadFlumotion():
    """Properly reload all flumotion-related modules currently loaded."""
    needs_reload = lambda name: name.startswith('flumotion')
    for name in filter(needs_reload, sys.modules.keys()):
        if not name in sys.modules:
            log.warning("reload", "hm, %s disappeared from the modules" % name)
            continue
        module = sys.modules[name]
        if not module:
            log.log("reload", "hm, module '%s' == None" % name)
            continue
        log.log("reload", "rebuilding %s" % module)
        try:
            rebuild(module, doLog=0)
        except SyntaxError, msg:
            from flumotion.common import errors
            raise errors.ReloadSyntaxError(msg)
コード例 #45
0
def reloadFlumotion():
    """Properly reload all flumotion-related modules currently loaded."""
    needs_reload = lambda name: name.startswith('flumotion')
    for name in filter(needs_reload, sys.modules.keys()):
        if not name in sys.modules:
            log.warning("reload", "hm, %s disappeared from the modules" % name)
            continue
        module = sys.modules[name]
        if not module:
            log.log("reload", "hm, module '%s' == None" % name)
            continue
        log.log("reload", "rebuilding %s" % module)
        try:
            rebuild(module, doLog=0)
        except SyntaxError, msg:
            from flumotion.common import errors
            raise errors.ReloadSyntaxError(msg)
コード例 #46
0
ファイル: ircd.py プロジェクト: ElementalAlchemist/txircd
	def loadModule(self, moduleName):
		"""
		Loads a module of the specified name.
		Raises ModuleLoadError if the module cannot be loaded.
		If the specified module is currently being unloaded, returns the
		DeferredList specified by the module when it was unloading with a
		callback to try to load the module again once it succeeds.
		"""
		if moduleName in self._unloadingModules:
			deferList = self._unloadingModules[moduleName]
			deferList.addCallback(self._tryLoadAgain, moduleName)
			return deferList
		for module in getPlugins(IModuleData, txircd.modules):
			if module.name == moduleName:
				rebuild(importlib.import_module(module.__module__)) # getPlugins doesn't recompile modules, so let's do that ourselves.
				self._loadModuleData(module)
				self.log.info("Loaded module {module}.", module=moduleName)
				break
コード例 #47
0
ファイル: main.py プロジェクト: MilkSR/WooferedBot
def keyboard_handler():
    print 'Hi, keyboard input here plz'
    while True:
        try:
            cmd = raw_input()
            if cmd == 'q': break
            elif cmd == ' ':
                command = raw_input("What do you want to do?:")
                if command.lower() == "join":
                    newChannel = raw_input("Which channel do you want to join?:")

                    if newChannel in config['channels']:
                        print 'We\'re already in channel #{}'.format(newChannel)
                    else:
                        # add to last bot, or create new bot if none exist yet
                        if len(bots) > 0:
                            (bot, tcp) = bots[-1]
                        else:
                            bot = WooferBotFactory([newChannel])
                            tcp = reactor.connectTCP("irc.twitch.tv", 6667, bot)
                            bots.append((bot, tcp))
                        bot.addChannel(newChannel)

                elif command.lower() == "chat":
                    channel = raw_input("Where do you want to chat?:")
                    # find bot associated to channel
                    try:
                        bot = next(bot for (bot,tcp) in bots if channel in bot.channels)
                        msg = raw_input("What do you want to say?:")
                        bot.irc.say(channel, msg)
                    except StopIteration:
                        print 'I don\'t know that channel'

                elif command.lower() == "reload":
                    rebuild(handler)
                    rebuild(api)
                
                elif command.lower() == "load":
                    loadChannel = raw_input("Which channel's config should I load?:")
                    config.load(loadChannel)
                    
        except Exception,e:
            print e
コード例 #48
0
    def connectionMade(self, irc, secret=None):
        self._irc = irc
        self.readState()
        try:
            helper = rebuild.rebuild(helper, doLog=0)
        except:
            pass

        self.periodic_commands = LoopingCall(self.do_periodics)
        self.periodic_commands.start(1800)
        self.loopers.append(self.periodic_commands)
コード例 #49
0
 def load_plugins(self):
     from twisted.plugin import getPlugins, IPlugin
     import plugins
     if not self.irc_auth.q_auth():
         print "Plugins failed to load"
         return
     else:
         for plugin in getPlugins(IPlugin, plugins):
             try:
                 for cmd, fun in plugin.commands.items():
                     object_path = plugin.__module__ + "." + plugin.name
                     # Could be un-needed.
                     #p_module = rebuild(self.my_import(plugin.__module__))
                     rebuild(self.my_import(plugin.__module__))
                     p_object = eval(object_path[5:])()
                     self.thoughts[cmd] = p_object.__getattribute__(fun)
             except AttributeError:
                 print "Error on importing plugins: " + str(plugin)
         for key, value in self.thoughts.items():
             print str(key) + " : " + str(value)
コード例 #50
0
    def testFileRebuild(self):
        from twisted.python.util import sibpath
        import shutil, time
        shutil.copyfile(
            sibpath(__file__, "myrebuilder1.py"),
            os.path.join(self.fakelibPath, "myrebuilder.py"))
        from twisted_rebuild_fakelib import myrebuilder
        a = myrebuilder.A()
        try:
            object
        except NameError:
            pass
        else:
            from twisted.test import test_rebuild
            b = myrebuilder.B()

            class C(myrebuilder.B):
                pass

            test_rebuild.C = C
            c = C()
        i = myrebuilder.Inherit()
        self.assertEquals(a.a(), 'a')
        # necessary because the file has not "changed" if a second has not gone
        # by in unix.  This sucks, but it's not often that you'll be doing more
        # than one reload per second.
        time.sleep(1.1)
        shutil.copyfile(
            sibpath(__file__, "myrebuilder2.py"),
            os.path.join(self.fakelibPath, "myrebuilder.py"))
        rebuild.rebuild(myrebuilder)
        try:
            object
        except NameError:
            pass
        else:
            b2 = myrebuilder.B()
            self.assertEquals(b2.b(), 'c')
            self.assertEquals(b.b(), 'c')
        self.assertEquals(i.a(), 'd')
        self.assertEquals(a.a(), 'b')
コード例 #51
0
ファイル: gtkmanhole.py プロジェクト: fxia22/ASM_xf
 def codeInput(self, text):
     methodName = 'do'
     if text[0] == '/':
         split = string.split(text[1:],' ',1)
         statement = split[0]
         if len(split) == 2:
             remainder = split[1]
         if statement in ('browse', 'explore'):
             methodName = 'explore'
             text = remainder
         elif statement == 'watch':
             methodName = 'watch'
             text = remainder
         elif statement == 'self_rebuild':
             rebuild.rebuild(explorer)
             if _GNOME_POWER:
                 rebuild.rebuild(spelunk_gnome)
             rebuild.rebuild(sys.modules[__name__])
             return
     try:
         self.perspective.callRemote(methodName, text)
     except pb.ProtocolError:
         # ASSUMPTION: pb.ProtocolError means we lost our connection.
         (eType, eVal, tb) = sys.exc_info()
         del tb
         s = string.join(traceback.format_exception_only(eType, eVal),
                         '')
         self.connectionLost(s)
     except:
         traceback.print_exc()
         gtk.mainquit()
コード例 #52
0
 def codeInput(self, text):
     methodName = 'do'
     if text[0] == '/':
         split = string.split(text[1:],' ',1)
         statement = split[0]
         if len(split) == 2:
             remainder = split[1]
         if statement in ('browse', 'explore'):
             methodName = 'explore'
             text = remainder
         elif statement == 'watch':
             methodName = 'watch'
             text = remainder
         elif statement == 'self_rebuild':
             rebuild.rebuild(explorer)
             if _GNOME_POWER:
                 rebuild.rebuild(spelunk_gnome)
             rebuild.rebuild(sys.modules[__name__])
             return
     try:
         self.perspective.callRemote(methodName, text)
     except pb.ProtocolError:
         # ASSUMPTION: pb.ProtocolError means we lost our connection.
         (eType, eVal, tb) = sys.exc_info()
         del tb
         s = string.join(traceback.format_exception_only(eType, eVal),
                         '')
         self.connectionLost(s)
     except:
         traceback.print_exc()
         gtk.mainquit()
コード例 #53
0
ファイル: test_rebuild.py プロジェクト: levanhong05/MeshMagic
    def testFileRebuild(self):
        from twisted.python.util import sibpath
        import shutil, time
        shutil.copyfile(sibpath(__file__, "myrebuilder1.py"),
                        os.path.join(self.fakelibPath, "myrebuilder.py"))
        from twisted_rebuild_fakelib import myrebuilder
        a = myrebuilder.A()
        try:
            object
        except NameError:
            pass
        else:
            from twisted.test import test_rebuild
            b = myrebuilder.B()

            class C(myrebuilder.B):
                pass

            test_rebuild.C = C
            c = C()
        i = myrebuilder.Inherit()
        self.assertEqual(a.a(), 'a')
        # necessary because the file has not "changed" if a second has not gone
        # by in unix.  This sucks, but it's not often that you'll be doing more
        # than one reload per second.
        time.sleep(1.1)
        shutil.copyfile(sibpath(__file__, "myrebuilder2.py"),
                        os.path.join(self.fakelibPath, "myrebuilder.py"))
        rebuild.rebuild(myrebuilder)
        try:
            object
        except NameError:
            pass
        else:
            b2 = myrebuilder.B()
            self.assertEqual(b2.b(), 'c')
            self.assertEqual(b.b(), 'c')
        self.assertEqual(i.a(), 'd')
        self.assertEqual(a.a(), 'b')
コード例 #54
0
ファイル: PluginFileEvent.py プロジェクト: wipepipe/Houdini
    def on_modified(self, event):
        pluginModuleDetails = evaluatePluginFileEvent(event)

        if not pluginModuleDetails:
            return

        pluginModulePath, pluginModule = pluginModuleDetails

        if pluginModule not in sys.modules:
            return

        self.logger.info("Reloading %s", pluginModule)

        xtHandlersCollection, xmlHandlersCollection = removeHandlersByModule(pluginModulePath)
        eventHandlersCollection = createDeepCopy(Events.EventHandlers)

        pluginModuleObject = sys.modules[pluginModule]
        pluginClass = pluginModuleObject.__name__.split(".")[2]

        try:
            removeEventsByInstance(pluginModuleObject)

            newPluginModule = rebuild.rebuild(pluginModuleObject)
            newPluginObject = getattr(newPluginModule, pluginClass)(self.server)
            self.server.plugins[pluginClass] = newPluginObject

            self.logger.info("Successfully reloaded %s!", pluginModule)

        except LookupError as lookupError:
            self.logger.warn("Did not reload plugin '%s': %s." % (pluginClass, lookupError.message))

        except Exception as rebuildError:
            self.logger.error("%s detected in %s, not reloading.", rebuildError.__class__.__name__, pluginModule)
            self.logger.info("Restoring handler references...")

            Handlers.XTHandlers = xtHandlersCollection
            Handlers.XMLHandlers = xmlHandlersCollection
            Events.EventHandlers = eventHandlersCollection

            self.logger.info("Handler references restored. Phew!")
コード例 #55
0
    def sendMessage(self, unused_data=None):
        text = self.get_chars(0,-1)
        if self.linemode:
            self.blockcount = self.blockcount + 1
            fmt = ">>> # begin %s\n%%s\n#end %s\n" % (
                self.blockcount, self.blockcount)
        else:
            fmt = ">>> %s\n"
        self.history.append(text)
        self.histpos = len(self.history)
        self.toplevel.output.console([['command',fmt % text]])

        method = self.toplevel.perspective.do

        if text[0] == '/':
            split = string.split(text[1:],' ',1)
            statement = split[0]
            if len(split) == 2:
                remainder = split[1]
            if statement == 'browse':
                method = self.toplevel.perspective.browse
                text = remainder
            elif statement == 'watch':
                method = self.toplevel.perspective.watch
                text = remainder
            elif statement == 'self_rebuild':
                rebuild.rebuild(explorer)
                if _GNOME_POWER:
                    rebuild.rebuild(gnomehole)
                rebuild.rebuild(sys.modules[__name__])
                return
        try:
            method(text)
        except pb.ProtocolError:
            # ASSUMPTION: pb.ProtocolError means we lost our connection.
            (eType, eVal, tb) = sys.exc_info()
            del tb
            s = string.join(traceback.format_exception_only(eType, eVal),
                            '')
            self.toplevel.connectionLost(s)
        except:
            traceback.print_exc()
            gtk.mainquit()
コード例 #56
0
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from collections import deque
from datetime import datetime, timedelta
from random import randint, choice
import cPickle
from os import fstat, stat, getpid
import re
import subprocess
import psycopg2
from time import time
from twisted.python.rebuild import rebuild

import markov
rebuild(markov)  # Update in case of dynamic reload

DEFAULT_MARKOV_LENGTH = 4  # Valid values:  1-4

CONTEXT_CHAIN_BIAS = 100  # Adjust response-ranking priority of chain
# length vs. context score (higher numbers
# favor longer chain length more)

#------------------------------------------------------------------------------


class Nikky_error(Exception):
    pass


class Dont_know_how_to_respond_error(Nikky_error):
コード例 #57
0
ファイル: test_dirdbm.py プロジェクト: stjordanis/twisted
 def test_rebuildInteraction(self):
     s = dirdbm.Shelf("dirdbm.rebuild.test")
     s[b"key"] = b"value"
     rebuild.rebuild(dirdbm)