if stdout is None:
    stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
code = """
i = [0,1,2]
for j in i :
    print j
"""
with stdoutIO() as s:
    exec(code)
print('out:', s.getvalue())
python: получить вывод на печать в операторе exec