create & read from tempfile

Python

Python Problem Overview


Is there anyway I could write to tempfile and include it in a command, and then close/remove it. I would like to execute the command, eg: some_command /tmp/some-temp-file.
Many thanks in advance.

import tempfile
temp = tempfile.TemporaryFile()
temp.write('Some data')
command=(some_command temp.name)
temp.close()

Python Solutions


Solution 1 - Python

Complete example.

import tempfile
with tempfile.NamedTemporaryFile() as temp:
    temp.write('Some data')
    if should_call_some_python_function_that_will_read_the_file():
       temp.seek(0)
       some_python_function(temp)
    elif should_call_external_command():
       temp.flush()
       subprocess.call(["wc", temp.name])

Update: As mentioned in the comments, this may not work in windows. Use this solution for windows

Update 2: Python3 requires that the string to be written is represented as bytes, not str, so do instead

temp.write(bytes('Some data', encoding = 'utf-8')) 

Solution 2 - Python

If you need a temporary file with a name you have to use the NamedTemporaryFile function. Then you can use temp.name. Read http://docs.python.org/library/tempfile.html for details.

Solution 3 - Python

Try this:

import tempfile
import commands
import os

commandname = "cat"

f = tempfile.NamedTemporaryFile(delete=False)
f.write("oh hello there")
f.close() # file is not immediately deleted because we
          # used delete=False

res = commands.getoutput("%s %s" % (commandname,f.name))
print res
os.unlink(f.name)

It just prints the content of the temp file, but that should give you the right idea. Note that the file is closed (f.close()) before the external process gets to see it. That's important -- it ensures that all your write ops are properly flushed (and, in Windows, that you're not locking the file). NamedTemporaryFile instances are usually deleted as soon as they are closed; hence the delete=False bit.

If you want more control over the process, you could try subprocess.Popen, but it sounds like commands.getoutput may be sufficient for your purposes.

Solution 4 - Python

Use a NamedTemporaryFile and its member name instead. A regular TemporaryFile isn't even guaranteed to have a name, due to the way Unix filesystems work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDGTView Question on Stackoverflow
Solution 1 - PythonbalkiView Answer on Stackoverflow
Solution 2 - PythonDennis BenzingerView Answer on Stackoverflow
Solution 3 - PythonphoojiView Answer on Stackoverflow
Solution 4 - PythonFred FooView Answer on Stackoverflow