Generator from function prints
<p>At the moment I have a little <code>flask</code> project that calls another python file. I'm fully aware that this way is kinda awful, and so, I want to swap it for a function call while maintaining <strong>the prints getting yelded to the website</strong>. </p>

<pre><code>def get_Checks():
    root = request.url_root

    def func():
        yield ("Inicio &lt;br&gt;")
        with subprocess.Popen(r"python somefile.py", stdout=subprocess.PIPE, bufsize=1,
                              universal_newlines=True) as p:
            for line in p.stdout:
                yield (line + "&lt;br&gt;")

    return Response(func())
</code></pre>

<p>I've tryed to replace the file call with the function directly but it just prints it to the console.</p>

<p>I really appreciate any help you can provide.</p>

<p>A simple way would be to temporarily change <code>sys.stdout</code> to a file-like object, call the function, then restore <code>sys.stdout</code>. The output will be available in the file-like object.</p>

<p>Here is a working Flask app that demonstrates the method:</p>

<pre><code>import sys
from io import StringIO
from flask import Flask, request, Response
import somefile

app = Flask(__name__)

@app.route("/")
def hello():
    def func():
        yield ("Inicio &lt;br&gt;")

        try:
            _stdout = sys.stdout
            sys.stdout = output = StringIO()
            somefile.main()
            output.seek(0)
            for line in output:
                sys.stdout = _stdout
                yield '{}&lt;br&gt;'.format(line.rstrip())
                sys.stdout = output
        finally:
            sys.stdout.close()    # close the StringIO object
            sys.stdout = _stdout  # restore sys.stdout

    return Response(func())

if __name__ == "__main__":
    app.run()
</code></pre>

<p>Here a <a href="https://docs.python.org/3/library/io.html?highlight=pipe#io.StringIO" rel="nofollow"><code>io.StringIO</code></a> object is used to collect the standard output produced by the function, and then the lines are yielded from that object. The <code>finally</code> ensures that the original <code>sys.stdout</code> is restored afterwards. There is some additional complexity around the <code>yield</code> statement because <code>yield</code> returns control to the calling code for which stdout must be restored in case the caller also wants to print to stdout.</p>

<p>It's assumed that the function in <code>somefile.py</code> is the "main" function, and that invocation of it is guarded by a <code>if __name__ == '__main__':</code> test, something like this:</p>

<pre><code>def main():
    for i in range(10):
        print(i)

if __name__ == '__main__':
    main()
</code></pre>

python python-3.x flask subprocess generator