Skip to content

Instantly share code, notes, and snippets.

@agrif
Created September 24, 2012 01:33
Show Gist options
  • Save agrif/3773742 to your computer and use it in GitHub Desktop.
Save agrif/3773742 to your computer and use it in GitHub Desktop.
import phosphorus
from phosphorus.irc import IRC
import sys
_, host, port, nick = sys.argv
def main():
irc = IRC(host, port, nick)
yield phosphorus.fork(irc.run())
yield phosphorus.until_elapsed(2)
yield from irc.send_command("join", "#overviewer")
while 1:
cmd = (yield from irc.get_next_command('privmsg'))
if not cmd:
break
source, message = cmd[1]
if source == "#overviewer":
if "fnord" in message.lower():
yield from irc.send_command("privmsg", "#overviewer", message.lower().replace("fnord", ""))
phosphorus.run(main())
@agrif
Copy link
Author

agrif commented Sep 24, 2012

def run(coroutine):
    try:
        iter(coroutine)
    except TypeError:
        raise TypeError("cannot run a non-iterable coroutine") from None

    # start with an always-true cond
    cond = until_all()

    # bring in parallel to handle forks
    coroutine = parallel(coroutine)

    # loop
    while 1:
        timeout = cond.get_max_timeout()
        rlist, wlist, xlist = cond.get_files()

        # do the select
        if timeout is not None:
            rlist, wlist, xlist = select.select(rlist, wlist, xlist, timeout)
        else:
            rlist, wlist, xlist = select.select(rlist, wlist, xlist)

        # if our condition is met, continue
        try:
            if cond.is_fulfilled(rlist, wlist, xlist):
                try:
                    cond = next(coroutine)
                except StopIteration as si:
                    return si.value[0]
        except Exception as e:
            try:
                cond = coroutine.throw(type(e), e.args)
            except StopIteration as si:
                return si.value[0]

@agrif
Copy link
Author

agrif commented Sep 24, 2012

class TimeCondition(Condition):
    def __init__(self, end_time):
        super(TimeCondition, self).__init__()
        self.end_time = end_time
    def is_fulfilled(self, rlist, wlist, xlist):
        return time.time() >= self.end_time
    def get_max_timeout(self):
        return self.end_time - time.time()

def until_elapsed(seconds):
    return TimeCondition(time.time() + seconds)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment