6

I'm learning Gevent, but can't get the value returned by the function called in a greenlet. The following code:

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

gives me the error:

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

What am I doing wrong, and how do I get the value from each greenlet?

tldr
  • 11,924
  • 15
  • 75
  • 120

1 Answers1

16

According to http://www.gevent.org/intro.html you want

def asynchronous():
    threads = [Greenlet.spawn(fetch, i) for i in range(10)]
    gevent.joinall(threads)
    print([thread.value for thread in threads])
Uri
  • 25,622
  • 10
  • 45
  • 72
Peter Gibson
  • 19,086
  • 7
  • 60
  • 64
  • thanks Peter! Could you help me with my other Gevent question: http://stackoverflow.com/questions/20580252/python-requests-module-throws-exception-with-gevent – tldr Dec 14 '13 at 06:07
  • `result = gevent.joinall(threads)` assigning to a name is not necessary though. – Babu Feb 11 '16 at 05:53
  • @Babu, yes looks like if you're not using the `timeout` keyword argument to `joinall` then you can ignore the result. – Peter Gibson Feb 11 '16 at 10:20