Created
January 18, 2020 07:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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