0
python async_io.py
給予本以下協同程序在python
error traceback (most recent call last): File "aysnc_io.py", line 64, in Task(get('/foo')) NameError: name 'get' is not defined
我使用的協同程序python2.7獲得併發處理和但它是在Task
類內部定義我收到錯誤get not defined
。
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()))
畫質得到(路徑):應獲得高清(個體經營,路徑)? – Alex
是的,我試過它沒有奏效@alex – rohit