開始使用免費開始

變更工作目錄

你正在使用一個開源函式庫,能讓你在自己的資料上訓練深度神經網路。不幸的是,在訓練過程中,這個函式庫會把檢查點模型(也就是僅在部分資料上已訓練完成的模型)寫到目前的工作目錄。你覺得這個行為很惱人,因為你不想一定得從模型要被儲存的那個目錄啟動腳本。

你決定寫一個 context manager 來解決這個問題:它會先變更目前的工作目錄,讓你建置模型,然後再把工作目錄重設回原本的位置。你需要確保在模型訓練期間就算發生錯誤,也不會影響把工作目錄重設回原本位置。

本練習屬於課程

Python 函式寫作

檢視課程

練習說明

  • 加上一個敘述,能處理在情境中可能發生的任何錯誤。
  • 再加上一個敘述,確保無論是否出現錯誤,都會呼叫 os.chdir(current_dir)

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def in_dir(directory):
  """Change current working directory to `directory`,
  allow the user to run some code, and change back.

  Args:
    directory (str): The path to a directory to work in.
  """
  current_dir = os.getcwd()
  os.chdir(directory)

  # Add code that lets you handle errors
  ____:
    yield
  # Ensure the directory is reset,
  # whether there was an error or not
  ____:
    os.chdir(current_dir)
編輯並執行程式碼