您现在的位置是:首页 >技术教程 >issue分享: cs231n assignment3在windows系统本地图片无法打开 (mkstemp()导致os.remove()报错)网站首页技术教程

issue分享: cs231n assignment3在windows系统本地图片无法打开 (mkstemp()导致os.remove()报错)

Tet_tet 2025-02-14 12:01:03
简介issue分享: cs231n assignment3在windows系统本地图片无法打开 (mkstemp()导致os.remove()报错)

问题

问题描述:tempfile.mkstemp()创建临时文件后试图os.remove()报错:文件被其他程序使用
起因是在cs231n的assignment3中,因为不习惯google colab一直本地部署的我第一次遇到源代码无法使用的问题
问题函数,让我作为一个初接触vision相关的小白大为头疼:

def image_from_url(url):
    """
    Read an image from a URL. Returns a numpy array with the pixel data.
    We write the image to a temporary file then read it back. Kinda gross.
    """
    try:
        f = urllib.request.urlopen(url)
        _, fname = tempfile.mkstemp()
        with open(fname, "wb") as ff:
            ff.write(f.read())
        img = imread(fname)
        os.remove(fname)
        return img
    except urllib.error.URLError as e:
        print("URL Error: ", e.reason, url)
    except urllib.error.HTTPError as e:
        print("HTTP Error: ", e.code, url)

在google colab上运行没有问题,然而本地运行的时候报错:
PermissionError: [WinError 32] 另一个程序正在使用此文件,进程无法访问。
试图探究后发现这个占用文件的程序竟然是
python.exe!!!

粗浅解决

一开始以为是imageio的imread()函数打开了文件没关闭,并经过不断查询发现github上也有描述类似问题,但用上面的解决方案没能解决,经过与LLM之神的反复磋商,它给出的解决方案为:
使用tempfile.NamdTemporaryFile(),然后再手动关闭文件,如下

def image_from_url(url):

    """

    Read an image from a URL. Returns a numpy array with the pixel data.

    We write the image to a temporary file then read it back. Kinda gross.

    """

    try:

        f=urllib.request.urlopen(url)

        temp_file=tempfile.NamedTemporaryFile(delete=False)

        temp_file.write(f.read())

        temp_file.close()

        img = imread(temp_file.name)

        os.remove(temp_file.name)

        return img

    except urllib.error.URLError as e:

        print("URL Error: ", e.reason, url)

    except urllib.error.HTTPError as e:

        print("HTTP Error: ", e.code, url)

这样确实可以解决问题,但是修改太大,不优雅

最终解决

在删除imread()后仍有问题,于是开始怀疑mkstemp(),稍作查询在stackoverflow上找到了答案:mkptemp()会以打开的形式创建文件,在google colab上是linux系统无所谓,但是Windows不能操作打开的文件是会报错的,于是只需稍加一句关闭即可。修改版:

def image_from_url(url):
    """
    Read an image from a URL. Returns a numpy array with the pixel data.
    We write the image to a temporary file then read it back. Kinda gross.
    """
    try:
        f = urllib.request.urlopen(url)
        fd, fname = tempfile.mkstemp()
        with open(fname, "wb") as ff:
            ff.write(f.read())
        img = imread(fname)
        os.close(fd)
        os.remove(fname)
        return img
    except urllib.error.URLError as e:
        print("URL Error: ", e.reason, url)
    except urllib.error.HTTPError as e:
        print("HTTP Error: ", e.code, url)

在这里插入图片描述

叠甲

如果有和我一样初经此道,不谙世事(对imageio,tempfile等库都从未接触过)的朋友遇到类似的问题,希望能有所帮助。其他在学习cs231n的朋友可以一起交流!也希望深谙此道的大佬勿觉愚蠢,指点一二!

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。