首页 > 解决方案 > 如何将控制台输出转换为 txt 文件(使用 python 烧瓶服务器)

问题描述

假设我有一个服务器代码,当调用函数 savePersonList() 时,控制台上打印的结果应该保存到一个文本文件中。

#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()

标签: python-3.xflask

解决方案


一般情况下,srinath samala 的答案是正确的,但正如您在评论中提到的,并非所有输出都重定向到文件。


这是因为 Flask 应用程序的某些输出被重定向到 STDERR,而不仅仅是 STDOUT。

要将两者都重定向到您的 txt 文件中,您需要使用以下命令:

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


推荐阅读