mmap为什么不关闭关联文件(获取PermissionError:[WinError 32])? [英] Why isn't mmap closing associated file (getting PermissionError: [WinError 32])?

查看:251
本文介绍了mmap为什么不关闭关联文件(获取PermissionError:[WinError 32])?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用将二进制数据读入其中的一些代码时在O'Reilly网站的Mutable Buffer 部分中,我在最后添加了一行以删除已创建的测试文件.

While experimenting with some of the code from the Reading Binary Data into a Mutable Buffer section of the O'Reilly website, I added a line at the end to remove the test file that was created.

但是,这总是导致以下错误:

However this always results in the following error:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'data'

我不了解这种行为,因为with memory_map(test_filename) as m:应该隐式关闭关联的文件,但显然不是.我可以通过保存从os.open()返回的文件描述符,然后在with套件中的语句块完成之后用os.close(fd)明确关闭它来解决此问题.

I don't understand this behavior because the with memory_map(test_filename) as m: should implicitly close the associated file, but apparently doesn't. I can work around this by saving the file descriptor returned from os.open() and then explicitly closing it with an os.close(fd) after the block of statements in the with suite finishes.

这是错误还是我错过了什么?

代码(带有两行注释掉的行显示了我的变通方法):

Code (with the couple of commented-out lines showing my hacky workaround):

import os
import mmap

test_filename = 'data'

def memory_map(filename, access=mmap.ACCESS_WRITE):
#    global fd  # Save to allow closing.
    size = os.path.getsize(filename)
    fd = os.open(filename, os.O_RDWR)
    return mmap.mmap(fd, size, access=access)

# Create test file.
size = 1000000
with open(test_filename, 'wb') as f:
     f.seek(size - 1)
     f.write(b'\x00')

# Read and modify mmapped file in-place.
with memory_map(test_filename) as m:
    print(len(m))
    print(m[0:10])
    # Reassign a slice.
    m[0:11] = b'Hello World'

# os.close(fd)  # Explicitly close the file descriptor -- WHY?

# Verify that changes were made
print('reading back')
with open(test_filename, 'rb') as f:
     print(f.read(11))

# Delete test file.
# Causes PermissionError: [WinError 32] The process cannot access the file
# because it is being used by another process: 'data'
os.remove(test_filename)

推荐答案

来自文档:

close()

关闭mmap.随后调用该对象的其他方法将导致引发ValueError异常.这不会关闭打开的文件.

close()

Closes the mmap. Subsequent calls to other methods of the object will result in a ValueError exception being raised. This will not close the open file.

内存映射独立于文件句柄.您可以将文件句柄用作常规文件.

The memory mapping is independent of the file handle. You can use the file handle as a normal file futher on.

这篇关于mmap为什么不关闭关联文件(获取PermissionError:[WinError 32])?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆