Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 965
jeromes Avatar asked Feb 09 '15 12:02

jeromes


1 Answers

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)
like image 128
jeromes Avatar answered Nov 15 '22 19:11

jeromes