简体   繁体   English

python中的协程

[英]Coroutines in python

python async_io.py 

Giving this following 给予以下

error traceback (most recent call last): File "aysnc_io.py", line 64, in Task(get('/foo')) NameError: name 'get' is not defined 错误回溯(最近一次调用最近):Task(get('/ foo'))中文件“ aysnc_io.py”,第64行,NameError:未定义名称“ get”

I am using python2.7 of coroutines to get concurrent processing and i am getting error get not defined however it is defined inside the Task class. 我正在使用协程的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()))

As I understand, you should move get definition outside of class 据我了解,您应该将get定义移到类之外

class Task:

        def __init__(self,gen):
            ...

        def step(self):
            ...

def get(path):
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM