如何在没有 file.close() 语句的情况下刷新 运行 python 进程中的文件写入缓冲区?

How to flush the file write buffer in running python process with no file.close() statement?

我有一个正在后台写入的文件 Python 3.5 进程。该文件在此过程中打开(基本上是一个 运行 Python 脚本),但我忘记在该脚本中包含一个文件关闭语句以偶尔清除缓冲区。该脚本是无限的,除非它被手动结束,我(现在)知道杀死 python 进程将导致缓冲区中的所有数据丢失。有没有办法恢复要写入这个已经 运行 进程的数据?

As per the docs

first do f.flush(), and then do os.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.

这是一个例子,

import os

with open("filename", "w") as f:
    while True:  # infinite program
        f.write("the text")
        f.flush()
        os.fsync(f.fileno())

1) 获取 python 进程的 PID

pgrep python

2) 列出文件描述符

ls -l /proc/{PID}/fd

3) 打开 gdb

$ gdb
(gdb) attach {PID}
(gdb) call fflush({FILE_DESCRIPTOR})
(gdb) detach

4) 检查您的文件