Try-Except-Finally 사원 건설
이 단계에서는 실행 중에 발생할 수 있는 모든 잠재적 실패를 견딜 수 있는 Python 파일을 생성하여 기록 보관자의 기반을 구축합니다. 이를 위해 Python 의 try, except, 그리고 finally 블록을 활용할 것입니다.
~/project에서 transcript_keeper.py라는 파일을 엽니다. 이 파일에 존재하지 않을 수 있는 파일에서 중요한 스크립트를 읽으려고 시도하는 Python 스크립트를 작성합니다. 파일이 없는 경우 예외를 처리하고, finally 블록을 사용하여 몇 가지 중요한 정리 작업이 수행되었음을 보장하는 메시지를 출력합니다.
다음은 transcript_keeper.py에 넣을 코드입니다.
def preserve_script():
try:
with open('/home/labex/project/sacred_script.txt', 'r') as file:
contents = file.read()
print(contents)
except FileNotFoundError:
print('The sacred script cannot be found.')
finally:
print('Ensuring the preservation environment remains intact.')
preserve_script()
이제 다음 명령을 사용하여 터미널에서 스크립트를 실행합니다.
python3 ~/project/transcript_keeper.py
sacred_script.txt가 존재하지 않으면 오류 메시지가 표시된 후 finally 블록 메시지가 표시됩니다.
The sacred script cannot be found.
Ensuring the preservation environment remains intact.