Exception safe context manager

Without the try/finally the cleanup could be skipped by an exception
being raised.
This commit is contained in:
Carlos Nihelton 2023-03-01 09:44:36 -03:00
parent babf0255b9
commit 33597e3c7d
No known key found for this signature in database
GPG Key ID: 6FE346D245197E9A
1 changed files with 7 additions and 5 deletions

View File

@ -34,7 +34,9 @@ def hostname_context(hostname: str):
back in the end of the caller scope. """ back in the end of the caller scope. """
hostname_current = gethostname() hostname_current = gethostname()
hostname_process = run_command(['hostname', hostname]) hostname_process = run_command(['hostname', hostname])
try:
yield hostname_process yield hostname_process
finally:
# Restoring the live session hostname. # Restoring the live session hostname.
hostname_process = run_command(['hostname', hostname_current]) hostname_process = run_command(['hostname', hostname_current])
if hostname_process.returncode: if hostname_process.returncode: