Vince Vince
Vince Vince

Reputation: 55

TemporaryFile is empty while script is running

I am trying to write into a temp file and use it in a subprocess. But it seems that the temp file is empty while the script is still running.

This is my code:

#!/usr/bin/python3
  
import subprocess
import tempfile

tmp = tempfile.NamedTemporaryFile(delete=False)
tmp.write(bytes("testcontent", encoding = 'utf-8'))
tmp_path = tmp.name
output = subprocess.run('cat ' + tmp_path, shell=True, capture_output=True)
print(tmp.name)
print(output.stdout)


existing_file = "/tmp/testfile"
output = subprocess.run('cat ' + existing_file, shell=True, capture_output=True)
print(output.stdout)

And this is the output:

/tmp/tmpllexuy_q
b''
b'testcontent\n'

When the script is finished the temp file exists and the content I wrote is also in the file:

cat /tmp/tmpllexuy_q
testcontent

If I use an already existing file that I created manually and wrote some content in, the subprocess call does work and gets the content of the file.

So is there something I am doing wrong? Maybe in the tempfile declaration "tempfile.NamedTemporaryFile(delete=False)"?

Upvotes: 1

Views: 140

Answers (1)

martineau
martineau

Reputation: 123393

If you add a tmp.flush() somewhere before the call to subprocess.run(), it will ensure that any buffered data there is be will actually be written the physical file. This worked for me when I tried it (after modifying it for Windows and successfully reproducing the problem).

Upvotes: 1

Related Questions