Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Getting value from Gevent Greenlet

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?

like image 913
tldr Avatar asked Dec 14 '13 04:12

tldr


People also ask

What is gevent greenlet?

gevent is a coroutine -based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev or libuv event loop. Features include: Fast event loop based on libev or libuv. Lightweight execution units based on greenlets.

What is greenlet in Python?

greenlet 1.1. 3 The “greenlet” package is a spin-off of Stackless, a version of CPython that supports micro-threads called “tasklets”. Tasklets run pseudo-concurrently (typically in a single or a few OS-level threads) and are synchronized with data exchanges on “channels”.

Is gevent asynchronous?

Gevent functions aren't running asynchronously.

What is gevent Eventlet?

gevent is a coroutine-based cooperative multitasking python framework that relies on monkey patching to make all code cooperative. Gevent actually draws its lineage from Eve Online which was implemented using Stackless Python which eventually evolved into eventlet which inspired gevent.


1 Answers

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])
like image 151
Peter Gibson Avatar answered Sep 24 '22 00:09

Peter Gibson