Skip to content

Instantly share code, notes, and snippets.

@aniljava
Last active November 20, 2017 15:40
Show Gist options
  • Save aniljava/11212614 to your computer and use it in GitHub Desktop.
Save aniljava/11212614 to your computer and use it in GitHub Desktop.
Gevent Seperate stdout per spawn
#!/usr/bin/env python2
# There should be a standard way of doing this. For now a hack.
import gevent
import inspect
def one():
print '1'
gevent.sleep(1)
print '2'
def two():
print '3'
print '4'
class FrameWriter:
def off(self):
sys.stdout = self.stdout
def on(self):
self.stdout = sys.stdout
sys.stdout = self
def __init__(self):
self.stdout = None
self.writers = {}
def write(self, obj):
caller = inspect.stack()[2][0].f_locals['self'] # Greenlets specific.
if not caller in self.writers:
self.writers[caller] = StringIO.StringIO()
self.writers[caller].write(obj)
def get_value(self, caller):
value = self.writers[caller].getvalue()
del self.writers[caller]
return value
import sys
import StringIO
frame_writer = FrameWriter()
frame_writer.on()
a = gevent.spawn(one)
b = gevent.spawn(two)
c = gevent.spawn(one)
# print one
gevent.joinall([a, b, c])
frame_writer.off()
print frame_writer.get_value(c)
@tiagocoutinho
Copy link

tiagocoutinho commented Jun 1, 2016

Great gist!
It inspired me to start writing gtools.
I stumbled across a problem that your example also suffers from:
It doesn't work if your function spawns a greenlet itself.

def one():
  def three():
    print 'hello'
  g = gevent.spawn(three).join()

Do you have any idea how to solve this?
It would be nice if a greenlet could know from which greenlet it was started from but as far as I know this doesn't exist in gevent.

Thanks in advance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment