Last active
October 9, 2015 13:29
-
-
Save michaelkuty/28969abec5c962507389 to your computer and use it in GitHub Desktop.
save output from celery tasks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
import sys | |
from StringIO import StringIO | |
def catch_result(task_func): | |
"""Catch printed result from Celery Task and return it in task response | |
""" | |
@functools.wraps(task_func) | |
def dec(*args, **kwargs): | |
# inicialize | |
orig_stdout = sys.stdout | |
sys.stdout = content = StringIO() | |
task_response = task_func(*args, **kwargs) | |
# catch | |
sys.stdout = orig_stdout | |
content.seek(0) | |
# propagate to the response | |
task_response['stdout'] = content.read() | |
return task_response | |
return dec | |
def catch_result_with_stdout(task_func): | |
"""Catch printed result | |
same as standard ``catch_result`` but provides ``stdout`` | |
variable as task argument | |
""" | |
@functools.wraps(task_func) | |
def dec(*args, **kwargs): | |
# inicialize | |
orig_stdout = sys.stdout | |
sys.stdout = content = StringIO() | |
# propagate down to the task | |
kwargs['stdout'] = content | |
task_response = task_func(*args, **kwargs) | |
# catch | |
sys.stdout = orig_stdout | |
content.seek(0) | |
# propagate to the response | |
task_response['stdout'] = content.read() | |
return task_response | |
return dec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment