Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

What is the `tempfile` module for?

IntermediateConceptExceptions, context managers, files & logging
Answer

It creates temp files and directories securely (unique names, 0600 permissions, no race with predictable /tmp/foo paths).

import tempfile
with tempfile.TemporaryDirectory() as d:
    subprocess.run(["git", "clone", "--depth=1", repo, d], check=True)
    ...  # directory deleted on exit

Never build temp paths by hand like /tmp/deploy.sh; another user can pre-create or symlink that path.

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging