cool! this worked wonderfully:
(setq org-babel-python-command "python -m sandbox")
#+BEGIN_SRC python
print 'hello'
print 4 + 6
import sys
print >>sys.stderr, 'message to stderr'
raise Exception('baboom')
#+END_SRC
#+RESULTS:
#+begin_example
--------------------------------------------------------------
hello
10
--------------------------------------------------------------
stderr:
message to stderr
--------------------------------------------------------------
Traceback (most recent call last):
File "/home/jkitchin/Dropbox/pycse/pycse/sandbox/sandbox.py", line 19, in <module>
exec(content, ns_globals, ns_locals)
File "<string>", line 10, in <module>
Exception: baboom
#+end_example
If anyone is interested, here is the sandbox module:
#!/usr/bin/env python
from cStringIO import StringIO
import os, sys
old_stdout = sys.stdout
old_stderr = sys.stderr
redirected_output = sys.stdout = StringIO()
redirected_error = sys.stderr = StringIO()
ns_globals = {}
ns_locals = {}
if __name__ == '__main__':
content = sys.stdin.read()
out, err, exc = None, None, None
try:
exec(content, ns_globals, ns_locals)
except:
import traceback
exc = traceback.format_exc()
out = redirected_output.getvalue()
err = redirected_error.getvalue()
sys.stdout = old_stdout
sys.stderr = old_stderr
s = '''
--------------------------------------------------------------
{0}
'''.format(out)
if err:
s += '''
--------------------------------------------------------------
stderr:
{0}
'''.format(err)
if exc:
s += '''
--------------------------------------------------------------
{0}
'''.format(exc)
print s