Python creates a temporary namedtemfile and calls a subprocess on it

I am having trouble creating a temporary file and then executing it. My process seems simple: - create a temporary file with tempfile.NamedTemporaryFile - write the bash command to the file - start the 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 busyon the check_call subprocess. How to use a temporary file to execute it?

+4
source share
1 answer

As stated in jester112358, this only requires closing the file. I was expecting the context to do this for me: \

Here 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)
+5
source

All Articles