[英]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
我的过程看起来很简单: - 使用tempfile.NamedTemporaryFile创建临时文件 - 将bash指令写入文件 - 启动子进程以执行创建的文件
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. 我得到
OSError: [Errno 26] Text file busy
子进程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. 正如jester112358指出的那样,它只需要关闭文件。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.