Skip to content

Instantly share code, notes, and snippets.

@bricef
Created January 18, 2020 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bricef/1bba6c56cd7e05fe52919d49da2fa831 to your computer and use it in GitHub Desktop.
Save bricef/1bba6c56cd7e05fe52919d49da2fa831 to your computer and use it in GitHub Desktop.
Given a value, create a temporary file and make this file available for the duration of the context.
class ValueContext(object):
"""
A ValueContext is constructed from a value that can be writtent to a file
and then exposes the value as a temporary file in its context.
The temporary file path can be accessed using its `name` attribute.
For example:
>>> with ValueContext("hello") as tmpfile:
... print(tmpfile.read())
... print(tmpfile.name)
hello
/tmp/XXXXXXXXX
"""
def __init__(self, value: str):
self.value = value
def __enter__(self):
self.file = tempfile.NamedTemporaryFile("w")
self.file.write(self.value)
self.file.flush()
os.fsync(self.file)
os.chmod(self.file.name, 0o600)
return self.file
def __exit__(self, *args):
self.file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment