If I write to a Python NamedTemporaryFile under specific conditions, the data written to the file cannot be read using the .seek(0) and then .read() methods. Is there a way to get this to work as expected?
Here is a case where data is written to the temp file using vi:
import subprocess
import tempfile
tf = tempfile.NamedTemporaryFile()
# Stop here and open file in vi on command line, write "test", and save.
tf.seek(0)
print(tf.read())
Here the output is empty, but the file does contain the data if you use cat from the command line on the file.
b''
Here is a case where data is written using the macOS screenshot command:
import subprocess
import tempfile
tf = tempfile.NamedTemporaryFile()
command = f'screencapture {tf.name}'
p = subprocess.run(command, shell=True)
tf.seek(0)
print(tf.read())
Again, here the output is empty, but the file is actually populated with PNG data. This can be tested by using head -c 4 command on the file.
b''
Here is one case where everything works as expected:
import subprocess
import tempfile
tf = tempfile.NamedTemporaryFile()
command = f'echo test > {tf.name}'
p = subprocess.run(command, shell=True)
tf.seek(0)
print(tf.read())
Output:
b'test\n'
The following code works, but does not use the temp file's handle to read. I am looking for an answer that uses the temp file's handle to seek and read etc.
import pathlib
import subprocess
import tempfile
with tempfile.NamedTemporaryFile() as tf:
subprocess.run(['screencapture', tf.name])
data = pathlib.Path(tf.name).read_bytes()