python - 在 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)
如果代码要读取整个文件,则需要在再次读取之前通过调用将文件指针移回文件开头。
推荐阅读
- pandas - 处理 pandas 的“尝试使用 .iloc”错误
- amazon-web-services - 无法获取 ECR 泊坞窗图像
- php - 我尝试播种我的播种器文件,但出现此错误
- python - 如何选择 NaN 行并将 value_A 分配给新列?代码 df.loc['condition_1' & 'condition_2' & 'df.column_a == ''] = 'value_a'
- python - 如何修复'''Mul'对象在Python中没有属性'sp'”错误(使用Sympy和Math)
- git - 将几行作为单独的提交更改分阶段
- spring - 使用轮询器测试直接通道和源的错误处理
- c# - 如何在 xamarin.forms 中为图像添加点击和长按手势?
- swift - 如何从/到 URL、Swift、MacOS 裁剪 Jpeg 图像
- c++ - 如何使用关键字签名在 CMake 上链接 opengl 库