Afshan Anwarali
Afshan Anwarali

Reputation: 357

How to get console output into a txt file (using python flask server)

Let's suppose I have a server code and when the function savePersonList() is called, the result printed on console should be saved into a text file.

#server coding

app = Flask(__name__)
def allowed_file(filename):
  # this has changed from the original example because the original did not work for me
    return filename[-3:].lower() in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET', 'POST']) #integrate code below function
def upload_file(): 

    if request.authorization and request.authorization.username == 'user1' and request.authorization.password == 'pass2': #login code line
        if request.method == 'POST':
            print("This is a post Request \n\n")
            file = request.files['file']
            if file and allowed_file(file.filename):
                print("File Sent is valid \n\n")
                print('**found file', file.filename)
                filename = secure_filename(file.filename) #use this from existing code before calling video capture 
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))  
    #code
                ''' This is the start of face recongition script '''
                CF.Key.set('d7c5495c64a44bc692761cd7c45ad56e')
                CF.BaseUrl.set('https://southeastasia.api.cognitive.microsoft.com/face/v1.0/')

                firstRun = True
                lastRun  = False

                #savePersonList()

Upvotes: 4

Views: 5149

Answers (3)

Astariul
Astariul

Reputation: 2354

The answer of srinath samala is correct in the general case, but as you mentionned on the comment, not all the output is redirected to the file.


This is because some output of your Flask app is redirected to STDERR, and not only STDOUT.

To redirect both into your txt file, you want to use this :

python app.py >> file.txt 2>&1

Upvotes: 6

srinath samala
srinath samala

Reputation: 210

if you are running on linux just use python app.py > file.txt(provided file.txt is created) might as well work on windows.

and add logger to your flask app as described in docs

so you can write it for each request yourself the file.txt then acts as your debug log.Hope it helps.

Upvotes: 2

A. Pine
A. Pine

Reputation: 331

You could redirect sys.stdout to be a file (see Redirect stdout to a file in Python?) but it might be better to use the logging module.

Upvotes: 0

Related Questions