Пример #1
0
def repeat(func, *args, **kwargs):
    """ Repeats a function in a new thread until it returns False """
    def run():
        while func(*args, **kwargs):
            pass

    pool.start(run)
Пример #2
0
def cacheGladefile(filename):
    """ gtk.glade automatically caches the file, so we only need to use this
        file once """
    if filename not in cachedGlades:
        cachedGlades[filename] = Queue.Queue()
        def readit ():
            glade = gtk.glade.XML(addDataPrefix("glade/%s" % filename))
            cachedGlades[filename].put(glade)
        pool.start(readit)
Пример #3
0
def cacheGladefile(filename):
    """ gtk.glade automatically caches the file, so we only need to use this
        file once """
    if filename not in cachedGlades:
        cachedGlades[filename] = Queue.Queue()

        def readit():
            glade = gtk.glade.XML(addDataPrefix("glade/%s" % filename))
            cachedGlades[filename].put(glade)

        pool.start(readit)
Пример #4
0
def cacheGladefile(filename):
    """ gtk.Builder automatically caches the file, so we only need to use this
        file once """
    if filename not in cachedGlades:
        cachedGlades[filename] = Queue.Queue()
        def readit ():
            builder = gtk.Builder()
            builder.set_translation_domain("pychess")
            builder.add_from_file(addDataPrefix("glade/%s" % filename))
            cachedGlades[filename].put(builder)
        pool.start(readit)
Пример #5
0
 def __onTell (self, chatManager, name, title, isadmin, text):
     
     if self.waitingForPassword:
         if text.strip() == self.password or (not self.password and text == "none"):
             self.sudos.add(name)
             self.tellHome("%s gained sudo access" % name)
             print >> self.connection.client, self.waitingForPassword
         else:
             chatManager.tellPlayer(name, "Wrong password")
             self.tellHome("%s failed sudo access" % name)
         self.waitingForPassword = None
         return
     
     args = text.split()
     
     #if args == ["help"]:
     #    chatManager.tellPlayer(name, self.__usage())
     
     if args[0] == "sudo":
         command = " ".join(args[1:])
         if name in self.sudos or name == self.owner:
             # Notice: This can be used to make nasty loops
             print >> self.connection.client, command
         else:
             print repr(name), self.sudos
             chatManager.tellPlayer(name, "Please send me the password")
             self.waitingForPassword = command
     
     elif args == ["sendlog"]:
         if self.log:
             # TODO: Consider email
             chatManager.tellPlayer(name, "\\n".join(self.log))
         else:
             chatManager.tellPlayer(name, "The log is currently empty")
     
     else:
         if self.ownerOnline:
             self.tellHome("%s told me '%s'" % (name, text))
         else:
             def onlineanswer (message):
                 data = urlopen("http://www.pandorabots.com/pandora/talk?botid=8d034368fe360895",
                                urlencode({"message":message, "botcust2":"x"})).read()
                 ss = "<b>DMPGirl:</b>"
                 es = "<br>"
                 answer = data[data.find(ss)+len(ss) : data.find(es,data.find(ss))]
                 chatManager.tellPlayer(name, answer)
             pool.start(onlineanswer, text)
Пример #6
0
    def __init__(self, path, args=[], warnwords=[], env=None):
        gobject.GObject.__init__(self)

        self.path = path
        self.args = args
        self.warnwords = warnwords
        self.env = env or os.environ
        self.buffer = ""

        self.linePublisher = EmitPublisher(self, "line",
                                           EmitPublisher.SEND_LIST)
        self.linePublisher.start()

        self.defname = os.path.split(path)[1]
        self.defname = self.defname[:1].upper() + self.defname[1:].lower()
        t = time.time()
        self.defname = (self.defname,
                        time.strftime("%H:%m:%%.3f", time.localtime(t)) %
                        (t % 60))
        log.debug(path + "\n", self.defname)

        argv = [str(u) for u in [self.path] + self.args]
        self.pid, stdin, stdout, stderr = gobject.spawn_async(
            argv,
            child_setup=self.__setup,
            standard_input=True,
            standard_output=True,
            standard_error=True,
            flags=gobject.SPAWN_DO_NOT_REAP_CHILD | gobject.SPAWN_SEARCH_PATH)

        self.__channelTags = []
        self.inChannel = self._initChannel(stdin, None, None, False)
        readFlags = gobject.IO_IN | gobject.IO_HUP  #|gobject.IO_ERR
        self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb,
                                            False)
        self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb,
                                            True)

        self.channelsClosed = False
        self.channelsClosedLock = threading.Lock()
        gobject.child_watch_add(self.pid, self.__child_watch_callback)

        self.subprocExitCode = (None, None)
        self.subprocFinishedEvent = threading.Event()
        self.subprocFinishedEvent.clear()
        subprocesses.append(self)
        pool.start(self._wait4exit)
Пример #7
0
 def __onTell (self, chatManager, name, title, isadmin, text):
     
     if self.waitingForPassword:
         if text.strip() == self.password or (not self.password and text == "none"):
             self.sudos.add(name)
             self.tellHome("%s gained sudo access" % name)
             self.connection.client.run_command(self.waitingForPassword)
         else:
             chatManager.tellPlayer(name, "Wrong password")
             self.tellHome("%s failed sudo access" % name)
         self.waitingForPassword = None
         return
     
     args = text.split()
     
     #if args == ["help"]:
     #    chatManager.tellPlayer(name, self.__usage())
     
     if args[0] == "sudo":
         command = " ".join(args[1:])
         if name in self.sudos or name == self.owner:
             # Notice: This can be used to make nasty loops
             print >> self.connection.client, command
         else:
             print repr(name), self.sudos
             chatManager.tellPlayer(name, "Please send me the password")
             self.waitingForPassword = command
     
     elif args == ["sendlog"]:
         if self.log:
             # TODO: Consider email
             chatManager.tellPlayer(name, "\\n".join(self.log))
         else:
             chatManager.tellPlayer(name, "The log is currently empty")
     
     else:
         if self.ownerOnline:
             self.tellHome("%s told me '%s'" % (name, text))
         else:
             def onlineanswer (message):
                 data = urlopen("http://www.pandorabots.com/pandora/talk?botid=8d034368fe360895",
                                urlencode({"message":message, "botcust2":"x"})).read()
                 ss = "<b>DMPGirl:</b>"
                 es = "<br>"
                 answer = data[data.find(ss)+len(ss) : data.find(es,data.find(ss))]
                 chatManager.tellPlayer(name, answer)
             pool.start(onlineanswer, text)
Пример #8
0
def repeat_sleep (func, sleeptime, recur=False):
    """ Runs func in a threadpool, and repeats it approximately each sleeptime [s].
        Notice that we sleep first, then run. Not the other way around.
        If repeat_sleep is called with recur=True, each call will be called with
        the return value of last call as argument. The argument has to be
        optional, as it wont be used first time, and it has to be non None. """
    def run ():
        last = time.time()
        val = None
        while True:
            time.sleep(time.time()-last + sleeptime)
            if not time:
                # If python has been shutdown while we were sleeping, the
                # imported modules will be None
                return
            last = time.time()
            if recur and val:
                val = func(val)
            else: val = func()
            if not val: break
    pool.start(run)
Пример #9
0
 def __init__(self, path, args=[], warnwords=[], env=None):
     gobject.GObject.__init__(self)
     
     self.path = path
     self.args = args
     self.warnwords = warnwords
     self.env = env or os.environ
     self.buffer = ""
     
     self.linePublisher = EmitPublisher(self, "line", EmitPublisher.SEND_LIST)
     self.linePublisher.start()
     
     self.defname = os.path.split(path)[1]
     self.defname = self.defname[:1].upper() + self.defname[1:].lower()
     t = time.time()
     self.defname = (self.defname,
                     time.strftime("%H:%m:%%.3f",time.localtime(t)) % (t%60))
     log.debug(path+"\n", self.defname)
     
     argv = [str(u) for u in [self.path]+self.args]
     self.pid, stdin, stdout, stderr = gobject.spawn_async(argv,
             child_setup=self.__setup,
             standard_input=True, standard_output=True, standard_error=True,
             flags=gobject.SPAWN_DO_NOT_REAP_CHILD|gobject.SPAWN_SEARCH_PATH)
     
     self.__channelTags = []
     self.inChannel = self._initChannel(stdin, None, None, False)
     readFlags = gobject.IO_IN|gobject.IO_HUP#|gobject.IO_ERR
     self.outChannel = self._initChannel(stdout, readFlags, self.__io_cb, False)
     self.errChannel = self._initChannel(stderr, readFlags, self.__io_cb, True)
     
     self.channelsClosed = False
     self.channelsClosedLock = threading.Lock()
     gobject.child_watch_add(self.pid, self.__child_watch_callback)
     
     self.subprocExitCode = (None, None)
     self.subprocFinishedEvent = threading.Event()
     self.subprocFinishedEvent.clear()
     subprocesses.append(self)
     pool.start(self._wait4exit)
Пример #10
0
def start_thread_dump ():
    def thread_dumper ():
        def dump_threads ():
            id2name = {}
            for thread in threading.enumerate():
                id2name[thread.ident] = thread.name
            
            stacks = []
            for thread_id, frame in sys._current_frames().items():
                stack = traceback.format_list(traceback.extract_stack(frame))
                if thread_id in gdklocks:
                    stacks.append("Thread GdkLock count: %s" % str(gdklocks[thread_id]))
                stacks.append("Thread: %s (%d)" % (id2name[thread_id], thread_id))
                stacks.append("".join(stack))
            
            log.debug("\n".join(stacks))
        
        while 1:
            dump_threads()
            time.sleep(10)
    
    pool.start(thread_dumper)
Пример #11
0
def repeat_sleep(func, sleeptime, recur=False):
    """ Runs func in a threadpool, and repeats it approximately each sleeptime [s].
        Notice that we sleep first, then run. Not the other way around.
        If repeat_sleep is called with recur=True, each call will be called with
        the return value of last call as argument. The argument has to be
        optional, as it wont be used first time, and it has to be non None. """
    def run():
        last = time.time()
        val = None
        while True:
            time.sleep(time.time() - last + sleeptime)
            if not time:
                # If python has been shutdown while we were sleeping, the
                # imported modules will be None
                return
            last = time.time()
            if recur and val:
                val = func(val)
            else:
                val = func()
            if not val: break

    pool.start(run)
Пример #12
0
def start_thread_dump():
    def thread_dumper():
        def dump_threads():
            id2name = {}
            for thread in threading.enumerate():
                id2name[thread.ident] = thread.name

            stacks = []
            for thread_id, frame in sys._current_frames().items():
                stack = traceback.format_list(traceback.extract_stack(frame))
                if thread_id in gdklocks:
                    stacks.append("Thread GdkLock count: %s" %
                                  str(gdklocks[thread_id]))
                stacks.append("Thread: %s (%d)" %
                              (id2name[thread_id], thread_id))
                stacks.append("".join(stack))

            log.debug("\n".join(stacks))

        while 1:
            dump_threads()
            time.sleep(10)

    pool.start(thread_dumper)
Пример #13
0
def repeat (func, *args, **kwargs):
    """ Repeats a function in a new thread until it returns False """
    def run ():
        while func(*args, **kwargs):
            pass
    pool.start(run)
Пример #14
0
 def gentleKill (self, first=1, second=1):
     if pool is not None:
         pool.start(self.__gentleKill_inner, first, second)
Пример #15
0
 def newFunction(*args, **kw):
     pool.start(f, *args, **kw)
Пример #16
0
 def run(self):
     pool.start(self.main)
     gtk.gdk.threads_init()
     gtk.main()
Пример #17
0
 def gentleKill(self, first=1, second=1):
     if pool is not None:
         pool.start(self.__gentleKill_inner, first, second)
Пример #18
0
 def start(self):
     if self.mode in (ANALYZING, INVERSE_ANALYZING):
         pool.start(self.__startBlocking)
     else:
         self.__startBlocking()
Пример #19
0
class Engine(Player):

    __type__ = ARTIFICIAL
    ''' The first argument is the pv list of moves. The second is a score
        relative to the engine. If no score is known, the value can be None,
        but not 0, which is a draw. '''
    __gsignals__ = {'analyze': (SIGNAL_RUN_FIRST, TYPE_NONE, (object, object))}

    def __init__(self):
        Player.__init__(self)

        self.currentAnalysis = []

        def on_analysis(self_, analysis, score):
            if score != None:
                self.currentScore = score
            self.currentAnalysis = analysis

        self.connect('analyze', on_analysis)

    #===========================================================================
    #    Offer handling
    #===========================================================================

    def offer(self, offer):
        raise NotImplementedError

    def offerDeclined(self, offer):
        pass  #Ignore

    def offerWithdrawn(self, offer):
        pass  #Ignore

    def offerError(self, offer, error):
        pass  #Ignore

    #===========================================================================
    #    General Engine Options
    #===========================================================================

    def setOptionAnalyzing(self, mode):
        self.mode = mode

    def setOptionInitialBoard(self, model):
        """ If the game starts at a board other than FEN_START, it should be
            sent here. We sends a gamemodel, so the engine can load the entire
            list of moves, if any """
        pass  # Optional

    def setOptionVariant(self, variant):
        """ Inform the engine of any special variant. If the engine doesn't
            understand the variant, this will raise an error. """
        raise NotImplementedError

    def setOptionTime(self, secs, gain):
        """ Seconds is the initial clock of the game.
            Gain is the amount of seconds a player gets after each move.
            If the engine doesn't support playing with time, this will fail."""
        raise NotImplementedError

    def setOptionStrength(self, strength):
        """ Strength is a number [1,8] inclusive. Higher is better. """
        self.strength = strength
        raise NotImplementedError

    #===========================================================================
    #    Engine specific methods
    #===========================================================================

    def canAnalyze(self):
        raise NotImplementedError

    def getAnalysis(self):
        """ Returns a list of moves, or None if there haven't yet been made an
            analysis """
        return self.currentAnalysis

    #===========================================================================
    #    General chat handling
    #===========================================================================

    def putMessage(self, message):
        def answer(message):
            try:
                data = urlopen(
                    "http://www.pandorabots.com/pandora/talk?botid=8d034368fe360895",
                    urlencode({
                        "message": message,
                        "botcust2": "x"
                    })).read()
            except IOError, e:
                log.warn("Couldn't answer message from online bot: '%s'\n" % e,
                         self.defname)
                return
            ss = "<b>DMPGirl:</b>"
            es = "<br>"
            answer = data[data.find(ss) + len(ss):data.find(es, data.find(ss))]
            self.emit("offer", Offer(CHAT_ACTION, answer))

        pool.start(answer, message)
Пример #20
0
        signal.signal(signal.SIGINT, gtk.main_quit)
        import gettext, gtk.glade
        from pychess.System.prefix import addDataPrefix, getDataPrefix, isInstalled
        if isInstalled():
            gettext.install("pychess", unicode=1)
            gtk.glade.bindtextdomain("pychess")
        else:
            gettext.install("pychess", localedir=addDataPrefix("lang"), unicode=1)
            gtk.glade.bindtextdomain("pychess", addDataPrefix("lang"))
        gtk.glade.textdomain("pychess")
        
        # Start logging
        from pychess.System.Log import log
        log.debug("Started\n")
        from pychess.widgets import LogDialog
        LogDialog.show()
        
    else:
        print "Unknown argument(s):", repr(sys.argv)
        sys.exit(0)
    
    pychess.makeReady()
    
    if len(sys.argv) == 5 and sys.argv[1] == "fics":
        from pychess.System.ThreadPool import pool
        pool.start(pychess.run)
        gtk.gdk.threads_init()
        gtk.main()
    else:
        pychess.run()
Пример #21
0
 def newFunction(*args, **kw):
     pool.start(f, *args, **kw)
Пример #22
0
 def start (self):
     if self.mode in (ANALYZING, INVERSE_ANALYZING):
         pool.start(self.__startBlocking)
     else:
         self.__startBlocking()