0
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()))
2
  • def get(path): Should be def get(self, path) ? Commented Sep 25, 2017 at 15:30
  • Yeah I tried that it didn't worked @alex Commented Sep 25, 2017 at 18:47

1 Answer 1

1

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

class Task:

        def __init__(self,gen):
            ...

        def step(self):
            ...

def get(path):
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.