如果>用于在Python中绕过控制台,则如何结束写入文件

问题描述 投票:0回答:2

所以我正在执行代码:

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)

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

python file-io read-write
2个回答
0
投票

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

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


0
投票

我设法通过运行以下命令解决此问题:

sys.stdout.flush()
© www.soinside.com 2019 - 2024. All rights reserved.