-
-
Save dstufft/9195493 to your computer and use it in GitHub Desktop.
| # Option 1 | |
| filename = None | |
| try: | |
| fileobj = tempfile.NamedTemporaryFile(delete=False) | |
| filename = fileobj.name | |
| fileobj.close() # Required because not all platforms can reopen a file a second time | |
| with open(filename, "w") as fp: | |
| fp.write(pkgutil.get_data("something.txt")) | |
| actually_call_a_thing(filename) | |
| finally: | |
| if filename is not None: | |
| os.remove(filename) | |
| # Option 2 | |
| with pkgutil.get_data_file("something.txt") as fileobj: | |
| actually_call_a_thing(fileobj.name) |
From the docs of tempfile.NamedTemporaryFile
Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later)
The above means that you have to close the file for it to work on Windows, which means you have to set delete=False. Also because there are GCs other than ref count you have to explicitly close it and not just wait for it to go out of scope, so you have to do the 3 line dance at the top instead of just filename = tempfile.NamedTemporaryFile(delete=False).name. Although I realized it could be simplified somewhat by doing:
filename = None
try:
with tempfile.NamedTemporaryFile(delete=False) as fileobj:
filename = fileobj.name
fileobj.write(pkgutil.get_data("something.txt"))
actually_call_a_thing(filename)
finally:
if filename is not None:
os.remove(filename)So that's not quite as annoying to do as my original snippet, but it's still not as nice as the second.
@dstufft what I do in those cases (we support windows pervasively at work), is something like
with tempfile.NamedTemporaryFile(delete=False) as fileobj:
filename = fileobj.name
although I prefer putting this in a separate function to make the intent (side effect) clearer
What's wrong with the following (I'm sure there's something I just don't know exactly what)?