Python mmap.write()不仅写入内存,还写入磁盘

时间:2018-02-02 14:47:28

标签: python windows memory-mapped-files

我在Windows上,使用mmap模块在两个Python脚本之间共享信息。我的问题是将数据写入内存以便从其他脚本访问,而无需将其写入磁盘。根据{{​​3}},mmap.write()方法正是我正在寻找的方法:将字节以字节为单位写入文件指针当前位置的内存并返回写入的字节数即可。

我正在运行以下代码来测试写入内存并遇到2个问题:

def test_write_mmf(json_path):

    # Know the file size to read from the memory
    file_size = os.path.getsize(json_path)

    # Open and read file amd MMF
    json_file = open(json_path, "r+", encoding="utf8")
    mapped_file = mmap.mmap(json_file.fileno(), 0)
    mapped_file.seek(0)
    buffer_for_json = mapped_file[:file_size]

    # Content is JSON, so load it
    json_data = json.loads(buffer_for_json.decode("utf-8"))

    # do some in-memory edits
    json_data[0]["response_index"] = 0
    json_data[0]["description"] = "INSTALL"

    # write it back into memory
    json_string = json.dumps(json_data)
    json_bytes = bytearray(json_string, encoding="utf8")
    mapped_file.seek(0)

    # It supposed to write into memory only!
    mapped_file.write(bytes(json_bytes))

    # Here I wait to check if the file was written
    m.getch()

    # Supposed to be real flush content to disk
    mapped_file.flush()
  1. 在第mapped_file.write(bytes(json_bytes))行,我预计我的更改仍在内存中,但它已存在于磁盘上的文件中。

  2. 这个问题与之前没有关联,但我意识到当书面内容比以前更小时,我看到" tail"之前的数据仍然保留在重写的文件中。有没有办法擦除打开的文件?我尝试使用权限被拒绝json_file.truncate()错误(WinError=13)

0 个答案:

没有答案