簡體   English   中英

將對象堅持到本地文件系統或S3

[英]Persist an object to either local file system or to S3

我需要一種將對象(模型)持久保存到本地文件系統或S3存儲桶的方法。 目的地由環境變量MODELS_DIR確定。 我有兩個版本,第一個版本更長一些,我對它的正確性很有信心。 第二個版本較短,但我擔心不使用with語句實際上是錯誤的。

def persist_model(model, model_name):
    """ VERSION 1
    Persist `model` under the name `model_name` to the environment variable
    `MODELS_DIR` (having a trailing '/').
    """
    MODELS_DIR = os.getenv('MODELS_DIR')

    if MODELS_DIR.startswith('s3://'):
        s3 = s3fs.S3FileSystem()
        with s3.open(MODELS_DIR[5:] + model_name, 'wb') as f:
            joblib.dump(model, f)
    else:
        with open(MODELS_DIR + model_name, 'wb') as f:
            joblib.dump(model, f)

和:

def persist_model(model, model_name):
    """VERSION 2
    Persist `model` under the name `model_name` to the environment variable
    `MODELS_DIR` (having a trailing '/').
    """
    MODELS_DIR = os.getenv('MODELS_DIR')

    if MODELS_DIR.startswith('s3://'):
        s3 = s3fs.S3FileSystem()
        f = s3.open(MODELS_DIR[5:] + model_name, 'wb')
    else:
        f = open(MODELS_DIR + model_name, 'wb')

    joblib.dump(model, f)

我的問題是第二版本是否可以安全使用?

是的,不。。。通常,您在寫入(轉儲)內容后需要關閉該文件。 當您使用with語句時,Python會注意這一點。 如果跳過with,則需要使用f.close()s.close()

另外,為確保即使在發生錯誤的情況下文件也被關閉,您將需要使用try-finally構造。 因此,如果正確使用第二個版本,它將比第一個更長。

為了避免代碼重復,我建議使用函數選擇器:

 def persist_model(model, model_name):

     def get_file_opener(path):
        if path.startswith('s3://'):
            return s3fs.S3FileSystem().open
        else 
            return open

     full_path = os.getenv('MODELS_DIR')
     with get_file_opener(fullpath)(fullpath[5:] + model_name, 'wb') as f:
        joblib.dump(model, f)

暫無
暫無

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

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