对于在 Python 中使用 > 绕过控制台的情况,如何结束写入文件

How can I end writing to file for cases where > is used to bypass console in Python

所以我正在执行代码:

python my_app.py > console.txt

这样我就可以在磁盘上生成一个包含所有控制台打印输出的文件。

然后在脚本的某处我想通过电子邮件发送报告。但每当我这样做时,我都会得到文件的截断版本。当应用程序关闭时,文件包含所有信息。

我试过这个:

 my_file = open('console.txt', 'r+', 1)
        my_file.flush()
        os.fsync(my_file.fileno())
        my_file.close()

        time.sleep(60)

        filename = 'console.txt'
        with open(filename, "r+", 1) as attachment:
            print(attachment.readline(-20))
            attachment.flush()
            os.fsync(attachment.fileno())

            time.sleep(60)
            # Add file as application/octet-stream
            # Email client can usually download this automatically as
            # attachment
            part = MIMEBase("application", "octet-stream")
            part.set_payload(attachment.read())
        attachment.close()

        # # Encode file in ASCII characters to send by email
        encoders.encode_base64(part)

        # Add header as key/value pair to attachment part
        part.add_header(
            "Content-Disposition",
            "attachment; filename={}".format(filename),
        )

        # Add attachment to message and convert message to string
        email.attach(part)

但是发送的文件仍然被截断了。关于如何将所有内容刷新到磁盘的任何想法或提示,我的手动触发器在这里不起作用:(

代码在 readline(-20) 语句中移动流位置(或文件指针)。

如果代码要读取整个文件,则在再次读取之前,需要通过调用 attachment.read(0) 将文件指针移回文件开头。

我通过 运行 解决了这个问题:

sys.stdout.flush()