【问题标题】:python create temp file namedtemporaryfile and call subprocess on itpython创建名为temporaryfile的临时文件并在其上调用子进程
【发布时间】:2015-02-09 12:44:32
【问题描述】:

我无法生成临时文件并在之后执行它。 我的过程似乎很简单: - 使用 tempfile.NamedTemporaryFile 创建临时文件 - 将 bash 指令写入文件 - 启动一个子进程来执行创建的文件

这里是实现:

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)

我在子进程 check_call 上收到 OSError: [Errno 26] Text file busy。 我应该如何使用临时文件才能执行它?

【问题讨论】:

  • 愚弄我...我期待with 上下文为我关闭文件,但事实并非如此。
  • NamedTemporaryFile 已经打开了文件(见docs.python.org/2/library/tempfile.html),这就是为什么我很惊讶上下文管理器上没有发生错误。此外,delete=True 参数会在您关闭连接时删除文件,这使得稍后在子进程中使用它是一种特殊用途。
  • 据我所知:临时文件在程序结束时被删除,而不是在文件关闭时被删除。我不确定这是正常行为还是我需要处理这种情况......

标签: python subprocess temporary-files


【解决方案1】:

正如 jester112358 所指出的,它只需要关闭文件。 我期待 with 上下文为我做这件事:\

这里有一个修复

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 2014-12-19
    • 2023-03-26
    • 2016-03-11
    相关资源
    最近更新 更多