rohit
rohit

Reputation: 49

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

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.

    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()))

Upvotes: 0

Views: 421

Answers (1)

kvorobiev
kvorobiev

Reputation: 5070

As I understand, you should move get definition outside of class

class Task:

        def __init__(self,gen):
            ...

        def step(self):
            ...

def get(path):
    ...

Upvotes: 1

Related Questions