首页 > 解决方案 > 在 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)

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

标签: pythonfile-ioread-write

解决方案


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

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


推荐阅读