在Python中的协同程序

时间:2017-09-25 05:51:37

标签: python python-2.7

python async_io.py 

给予以下

  

错误追溯(最近一次调用最后一次):文件“aysnc_io.py”,第64行,在任务中(get('/ foo'))NameError:名称'get'未定义

我正在使用corthon的python2.7来获取并发处理,我收到错误get not defined但是它是在Task类中定义的。

    from selectors2 import DefaultSelector,EVENT_WRITE,EVENT_READ
    import socket
    import time

    selector=DefaultSelector()
    global n_tasks

    n_tasks=0

    class Future:
        def __init__(self):
            self.callbacks=[]
        def resolve(self):
            for c in self.callbacks:
                c()


    class Task:

        def __init__(self,gen):
            self.gen=gen
            self.step()

        def step(self):
            try:
                f=next(self.gen)
            except StopIteration:
                return
            f.callbacks.append(self.step)

        def get(path):
            n_tasks +=1
            s=socket.socket()
            s.setblocking(False)
            try:
                s.connect(('localhost',80))
            except BlockingIOError:
                pass
            request ='GET %s HTTP/1.0 \r\n\r\n' % path
            f=Future()
            selector.register(s.fileno(),EVENT_WRITE,data=f)
            #need to pause s until it is writable
            yield f
            selector.unregister(s.fileno())
            #s is writable
            s.send(request.encode())
            chunks=[]
            while TRUE:
                f=Future()
                selector.register(s.fileno(),EVENT_READ,data=f)
                yield f
                selector.unregister(s.fileno())
                chunk=s.recv(1000)
                if chunk:
                    chunk.append(chunk)
                else:
                    body=(b''.join(chunks)).decode()
                    print(body.split('\n')[0])
                    n_tasks-=1
                    return


    start=time.time()
    Task(get('/www.google.com')) 
    while n_tasks:
        events=selector.select()
        for event,mask in events:
            fut=event.data
            fut.resolve()
    print('executed %.lf seconds' % (time.time()-start()))

1 个答案:

答案 0 :(得分:1)

据我了解,您应该将get定义移到课堂外

class Task:

        def __init__(self,gen):
            ...

        def step(self):
            ...

def get(path):
    ...