2013-12-14 37 views
3

我在學習Gevent,但無法獲得由greenlet中調用的函數返回的值。下面的代碼:Python:從Gevent Greenlet獲得價值

import gevent.monkey 
gevent.monkey.patch_socket() 

import gevent 
from gevent import Greenlet 

import urllib2 
import simplejson as json 

def fetch(pid): 
    response = urllib2.urlopen('http://time.jsontest.com') 
    result = response.read() 
    json_result = json.loads(result) 
    datetime = json_result['time'] 

    print('Process %s: %s' % (pid, datetime)) 
    return json_result['time'] 

def synchronous(): 
    for i in range(1,10): 
     fetch(i) 

def asynchronous(): 
    threads = [Greenlet.spawn(fetch, i) for i in range(10)] 
    result = gevent.joinall(threads) 
    print [Greenlet.value(thread) for thread in threads] 

print('Synchronous:') 
synchronous() 

print('Asynchronous:') 
asynchronous() 

給我的錯誤:

print [Greenlet.value(thread) for thread in threads] 
AttributeError: type object 'Greenlet' has no attribute 'value' 

我在做什麼錯了,我如何才能從每個greenlet的價值?

回答

7

根據http://www.gevent.org/intro.html你想

def asynchronous(): 
    threads = [Greenlet.spawn(fetch, i) for i in range(10)] 
    result = gevent.joinall(threads) 
    print [thread.value for thread in threads] 
+0

感謝彼得!你能幫助我與我的其他Gevent問題:http://stackoverflow.com/questions/20580252/python-requests-module-throws-exception-with-gevent – tldr

+0

結果= gevent.joinall(線程)'分配給一個名稱雖然沒有必要。 – Babu

+0

@Babu,看起來像是如果你不使用'timeout'關鍵字參數來'joinall',那麼你可以忽略結果。 –