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 ?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With