简体   繁体   English

Python 3.9:OSError:[Errno 9] 临时文件期间的文件描述符错误

[英]Python 3.9: OSError: [Errno 9] Bad file descriptor during Temporary File

I am trying to retrieve an image from S3 and do some processing with it:我正在尝试从 S3 检索图像并对其进行一些处理:

s3 = image_aws_session().client("s3")
with tempfile.TemporaryFile() as tmp:
    with open(tmp.name, "r+b") as f:
        s3.download_fileobj(
            Bucket=settings.S3_IMAGE_BUCKET,
            Key=s3_key,
            Fileobj=f,
        )
        f.seek(0)
        image_str = f.read().hex()
        print(image_str)
return image_str

I get a file back, and it also prints a nice long hash, so the fetching itself works.我取回了一个文件,它还打印了一个不错的长 hash,因此获取本身可以工作。 I had to obstruct the s3 key, since its not important.我不得不阻止 s3 键,因为它不重要。

However, then it errors out with OSError: [Errno 9] Bad file descriptor before returning the image hash.但是,在返回图像 hash 之前,它会出现OSError: [Errno 9] Bad file descriptor错误。 I have tried indenting back and forth to no avail.我试过来回缩进无济于事。 Maybe I am just not understanding something correctly也许我只是没有正确理解某些东西

  1. You're opening the file in read binary mode, but download_fileobj attempts to write to it, that wouldn't work.您正在以读取二进制模式打开文件,但download_fileobj尝试写入它,这是行不通的。 Also, you're appending to it by including + which probably isn't necessary.此外,您通过包含+来附加它,这可能不是必需的。 Try open('wb')尝试open('wb')
  2. It's possible that the file isn't updated after download_fileobj completes. download_fileobj完成后文件可能未更新。 Try letting it close after the download and reopening it下载后尝试关闭并重新打开
s3 = image_aws_session().client("s3")
with tempfile.TemporaryFile() as tmp:
    with open(tmp.name, "wb") as f:
        s3.download_fileobj(
            Bucket=settings.S3_IMAGE_BUCKET,
            Key=s3_key,
            Fileobj=f,
        )
    with open(tmp.name, 'rb') as f:
        image_str = f.read().hex()
        print(image_str)

return image_str

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM