Python:从Gevent Greenlet获得价值

前端之家收集整理的这篇文章主要介绍了Python:从Gevent Greenlet获得价值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在学习Gevent,但无法获得greenlet中调用函数返回的值.以下代码

  1. import gevent.monkey
  2. gevent.monkey.patch_socket()
  3. import gevent
  4. from gevent import Greenlet
  5. import urllib2
  6. import simplejson as json
  7. def fetch(pid):
  8. response = urllib2.urlopen('http://time.jsontest.com')
  9. result = response.read()
  10. json_result = json.loads(result)
  11. datetime = json_result['time']
  12. print('Process %s: %s' % (pid,datetime))
  13. return json_result['time']
  14. def synchronous():
  15. for i in range(1,10):
  16. fetch(i)
  17. def asynchronous():
  18. threads = [Greenlet.spawn(fetch,i) for i in range(10)]
  19. result = gevent.joinall(threads)
  20. print [Greenlet.value(thread) for thread in threads]
  21. print('Synchronous:')
  22. synchronous()
  23. print('Asynchronous:')
  24. asynchronous()

给我错误

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

我做错了什么,如何从每个greenlet中获取价值?

最佳答案
根据你想要的http://www.gevent.org/intro.html

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

猜你在找的Python相关文章