Redirecting output of script called from within Flask, into its own log file
Question: One of the user options in my Flask application is to trigger a web-scrape.
The output of this process (and indeed _any_ external process, and the output
of the main Flask app itself) is stdout which is the terminal in which I've
started my main Flask app.

I wish to maintain the overall Flask log in the terminal, while forcing the
log from the scraping process into its own file (for downloading). So given:

    
    
    @app.route("/download-log", methods=["GET"])
    def downloadlog():
        # Check for valid file and assign it to `inbound_file`
        with open('log.txt', 'r') as log:
            contents = log.read()
            response = make_response(contents)
            response.headers["Content-Disposition"] = "attachment; filename=log.txt"
            return response
    

.. which is working well, I need **log.txt** (currently just a `touch`ed file
for proof-of-concept) to be the log from the scraping process, which I call
thus:

    
    
    @app.route('/scrape', methods=['GET', 'POST'])
    @login_required                                 # Use of @login_required decorator
    def scrape():
        scraper.scrape('/path/to/URLs.csv', ['manager'])
    

where `scraper` is a standalone python script that can and does run off its
own bat normally, but is being called from within the Flask app here. I know
how to redirect stdout into a file when calling a script itself, but how can I
get the stdout of scraper.py into a file when it has been invoked from the
Flask app?


Answer: edit scraper.py and add a redirect to a log file:

    
    
    import sys
    sys.stdout = sys.stderr = open('log.txt','wt')
    

