Issue
I would like to redirect sys.stdout
to a Jinja variable so that I can see it in the frontend (I'm using Flask server). How do I do this? Is there a better way to get the stdout to the HTML template?
This is what I have tried:
sys.stdout = jinja2.Template("<div id='console'>{{ console }}</div>")
But I get this error when using print
:
AttributeError: 'Template' object has no attribute 'write'
Exception ignored in: <Template memory:b4a2a9f0>
AttributeError: 'Template' object has no attribute 'flush'
I've seen posts like this, but I'm not sure how to implement it in my case. Any help is appreciated.
Solution
If I understand what you would like to do you should write something similar (then adjust it according to your needs):
import sys
from io import StringIO
import jinja2
from flask import Flask
app = Flask(__name__)
@app.route("/test")
def home():
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
print("test")
sys.stdout = old_stdout
return jinja2.Template("<div id='console'>my output = {{ console }}</div>").render(
console=mystdout.getvalue()
)
if __name__ == "__main__":
app.run("0.0.0.0", 80, True)
Answered By - Matteo Pasini
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.