简体   繁体   English

如何在Flask中将控制台输出写入文本文件?

[英]How to write console output to text file in Flask?

I am using Ubuntu, python3 and Flask server. 我正在使用Ubuntu,python3和Flask服务器。 I simply want the line print('**found file', file.filename, '\\n') which is printed on terminal to be saved into a text file. 我只是希望将打印在终端上的行print('** found file',file.filename,'\\ n')保存到文本文件中。

Any kind of help would be appreciated. 任何帮助将不胜感激。 Thanks in advance. 提前致谢。

import os
from flask import Flask, request, redirect, url_for, send_from_directory, jsonify
from werkzeug import secure_filename

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'mp4'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

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'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            print('**found file', file.filename, '\n')
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return jsonify({"success" : url_for('uploaded_file',
                                    filename=filename)})
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

if __name__ == '__main__':
    app.run(host= '0.0.0.0', debug=True)

You can open a log file in append mode and add line every time print is called 您可以在追加模式下打开日志文件,并在每次调用打印时添加行

with open("server.log", "a") as fd:
    fd.write("**found file {} \n".format(file.filename))

Or you can redirect the standard output to the log file when you launch your programm 或者,您可以在启动程序时将标准输出重定向到日志文件

$ python run.py > server.log

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM