簡體   English   中英

Python 3.9:OSError:[Errno 9] 臨時文件期間的文件描述符錯誤

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

我正在嘗試從 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

我取回了一個文件,它還打印了一個不錯的長 hash,因此獲取本身可以工作。 我不得不阻止 s3 鍵,因為它不重要。

但是,在返回圖像 hash 之前,它會出現OSError: [Errno 9] Bad file descriptor錯誤。 我試過來回縮進無濟於事。 也許我只是沒有正確理解某些東西

  1. 您正在以讀取二進制模式打開文件,但download_fileobj嘗試寫入它,這是行不通的。 此外,您通過包含+來附加它,這可能不是必需的。 嘗試open('wb')
  2. download_fileobj完成后文件可能未更新。 下載后嘗試關閉並重新打開
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