簡體   English   中英

用於上傳到谷歌雲存儲的子進程 CALL 或 python 庫?

[英]Subprocess CALL or python library for uploading to Google Cloud Storage?

我正在嘗試編寫一個腳本來將文件上傳到 Google Cloud Storage。 我注意到有兩種方法可以做到這一點:

a) 使用 gsutil 並使用子進程從 python 調用它 b) 使用 from google.cloud import storage 和“native”方法。

每種方法的優點/缺點是什么? (a) 方法似乎更簡單,但我不知道與 b) 方法相比是否有任何缺點。

謝謝!

(a) 的例子

filename='myfile.csv'
gs_bucket='my/bucket'
parallel_threshold='150M' # minimum size for parallel upload; 0 to disable

subprocess.check_call([
  'gsutil',
  '-o', 'GSUtil:parallel_composite_upload_threshold=%s' % (parallel_threshold,),
  'cp', filename, 'gs://%s/%s' % (gs_bucket, filename)
])

(b) 的例子

from google.cloud import storage
def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    # bucket_name = "your-bucket-name"
    # source_file_name = "local/path/to/file"
    # destination_blob_name = "storage-object-name"

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

    blob.upload_from_filename(source_file_name)

    print(
        "File {} uploaded to {}.".format(
            source_file_name, destination_blob_name
        )
    )

最重要的是,您應該只選擇最適合您喜好的方法。 如果這兩種方式都適合您,那么這是一個偏好問題。

但是,如果您打算在除已正確安裝和配置 gsutil 的機器之外的任何地方運行此代碼,就會遇到問題。 它變成了一個外部依賴項,你可能不喜歡嘗試在它已經工作的地方之外的任何地方設置它。

如果您想更輕松地移動此代碼,則客戶端庫更可預測,並且應該在有 inte.net 連接的任何地方運行,假設您有服務帳戶憑據可用於您的代碼以初始化 SDK。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM