更改工作目录
您正在使用一个开源库来在您的数据上训练深度神经网络。不巧的是,训练过程中,该库会将检查点模型(即仅在部分数据上训练过的模型)写入当前工作目录。这个行为让您很困扰,因为您并不想总是从将要保存模型的目录来启动脚本。
您决定编写一个上下文管理器来解决这个问题:进入上下文时更改当前工作目录,允许您构建模型,退出时再将工作目录重置到原来的位置。您需要确保在模型训练过程中即使发生错误,也不会影响将工作目录重置回初始位置。
本练习是课程的一部分
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)