ipython/ipython — pull request #2051 by jasongrout (2012-06-28 20:52:19+00:00)
Title: Add a metadata attribute to zeromq stdout/stderr stream messages

We'd like to attach some metadata to stdout and stderr messages, for example, indicating where
the frontend should put the output. It would be really convenient if sys.stdout and sys.stderr (which I think is
IPython.zmq.iostream.OutStream, right?) had a 'metadata' attribute that could be set and would be added to each outgoing message. This would also change the messaging spec to add a 'metadata' attribute to the
content dict for stream messages (just like display_data messages already have).
```
@contextmanager
def stream_metadata(metadata):
sys.stdout.flush()
stdout_metadata = sys.stdout.metadata
old_stdout_metadata = stdout_metadata.copy()
stdout_metadata.update(metadata)
sys.stdout.set_metadata(stdout_metadata)

sys.stderr.flush()
stderr_metadata = sys.stderr.metadata
old_stderr_metadata = stderr_metadata.copy()
stderr_metadata.update(metadata)
sys.stderr.set_metadata(stderr_metadata)
try:
yield None
finally:
sys.stdout.set_metadata(old_stdout_metadata)
sys.stdout.set_metadata(old_stderr_metadata)

with stream_metadata({'location': 4}):
print 'hello world' # goes to location 4
```