jeromes
jeromes

Reputation: 517

python create temp file namedtemporaryfile and call subprocess on it

I'm having trouble generating a temp file and executing it afterward. My process seems simple: - create temp file with tempfile.NamedTemporaryFile - write bash instruction to the file - start a subprocess to execute the created file

Here is the implementation:

from tempfile import NamedTemporaryFile
import os
import subprocess

scriptFile = NamedTemporaryFile(delete=True)
with open(scriptFile.name, 'w') as f:
  f.write("#!/bin/bash\n")
  f.write("echo test\n")
  os.chmod(scriptFile.name, 0777)

subprocess.check_call(scriptFile.name)

I get OSError: [Errno 26] Text file busy on subprocess check_call. How should I use the temp file to be able to execute it ?

Upvotes: 13

Views: 5880

Answers (1)

jeromes
jeromes

Reputation: 517

As jester112358 pointed, it only requires the file to be closed. I was expecting the with context to do this for me :\

Here's a fix

from tempfile import NamedTemporaryFile
import os
import subprocess

scriptFile = NamedTemporaryFile(delete=True)
with open(scriptFile.name, 'w') as f:
  f.write("#!/bin/bash\n")
  f.write("echo test\n")

os.chmod(scriptFile.name, 0777)
scriptFile.file.close()

subprocess.check_call(scriptFile.name)

Upvotes: 14

Related Questions