【问题标题】:How to fix "No Such File or Directory" in /tmp folder in Google Cloud Functions - Python如何修复 Google Cloud Functions 中 /tmp 文件夹中的“没有这样的文件或目录” - Python
【发布时间】:2019-12-31 01:08:05
【问题描述】:

我需要将文件保存到 Google Cloud Functions 中的 tmp 文件夹。我正在从 Google Cloud Storage 访问该文件,然后将其发送到 Cloud Functions 以处理该文件。它是一个 MP4 文件,所以我不能使用任何可用于纯文本文件的功能。

我相信我唯一的两个选择是检索文件的二进制文件,我无法在任何地方找到记录,或者将文件保存到 tmp 文件夹,但这个 tmp 文件夹在内存中运行。但是,我找不到太多关于此的文档。

我找到的最好的是:tmp file in Google cloud Functions for Python,但是由于我没有使用文本文件,我无法让它工作。

我经常收到文件或目录不存在的错误。

我的代码如下所示(几乎与tmp file in Google cloud Functions for Python 相同)

def function(file):
    name = uploadedFile['name']
    path_name = get_file_path(name)


def get_file_path(file_name):
    return os.path.join(tempfile.gettempdir(), file_name)

我删除了一些特定于文本文件的行。

我不确定是否必须手动启用 tmp/ 文件夹,或者是否有其他方法可以解决此问题,但每当我运行该函数并提供文件时,我都会收到 FileNotFoundError: [Errno 2] No such file or directory: '/tmp/filename.mp4'

我假设发生了 2 件事中的 1 件事,1) 在文件完成运行之前正在执行下一行代码被复制(异步运行),或者 2 我必须做一些事情才能启用并能够写入 tmp 文件夹。

谢谢。

【问题讨论】:

  • /tmp 是否已经存在?
  • @FamousAv8er 我相信它已经是了,因为我找不到任何相反的文档,也找不到任何可以让我启用它的文档。
  • 目录存在,在内存目录中。但是,在阅读文件之前,你在写吗?这部分代码在哪里?将文件写入 /tmp/ 时有问题吗?
  • 你能在你实际读/写文件的地方包含代码吗?

标签: python google-cloud-functions


【解决方案1】:

首先是从 Google 云存储中以 Blob 形式检索文件,然后转换并下载到 /tmp。您将需要google.cloud 导入存储,这需要requirements.txt 文件中的google-cloudgoogle-cloud-storage

bucket_name = "bucket-name"
source_blob_name = "audio-file.wav"
destination_file_name = "/tmp/audio-file.wav

storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)

blob = bucket.blob(source_blob_name)
blob.download_to_filename(destination_file_name)

现在您只需要读取/tmp 文件夹。就我而言,它是一个音频文件,所以我使用scipy:

scipy.io.wavfile.read('/tmp/audio-file.wav')

我认为 Google 的文档在这方面有点误导,因为它实际上根本不需要使用 os.path

参考:https://cloud.google.com/functions/docs/concepts/exec#functions-concepts-filesystem-python

如果文件夹结构匹配,您还可以使用 ZIP 将静态文件传递到 /tmp。但是,您不会在控制台的任何位置看到此 tmp 文件夹,但它就在那里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2019-03-22
    • 1970-01-01
    • 2020-03-01
    相关资源
    最近更新 更多