【问题标题】:create & read from tempfile从 tempfile 创建和读取
【发布时间】:2011-03-17 19:39:23
【问题描述】:

无论如何我可以写入临时文件并将其包含在命令中,然后关闭/删除它。我想执行命令,例如:some_command /tmp/some-temp-file。
非常感谢。

import tempfile
temp = tempfile.TemporaryFile()
temp.write('Some data')
command=(some_command temp.name)
temp.close()

【问题讨论】:

    标签: python


    【解决方案1】:

    完整示例。

    import tempfile
    with tempfile.NamedTemporaryFile() as temp:
        temp.write('Some data')
        if should_call_some_python_function_that_will_read_the_file():
           temp.seek(0)
           some_python_function(temp)
        elif should_call_external_command():
           temp.flush()
           subprocess.call(["wc", temp.name])
    

    更新:如 cmets 中所述,这可能不适用于 Windows。 windows 使用this 解决方案

    更新 2:Python3 要求将要写入的字符串表示为字节,而不是 str,所以改为

    temp.write(bytes('Some data', encoding = 'utf-8')) 
    

    【讨论】:

    • 只想补充一点,如果命令被一些 Python 代码(如函数调用)替换,请确保执行 temp.seek(0),这样如果该函数尝试读取内容,它将不会不要空手而归。
    • +1 用于 withdocumentation 中的示例不使用 with 是否有原因?
    • 请确保您从docs 考虑这一点:“在命名的临时文件仍处于打开状态的情况下,是否可以使用该名称再次打开文件,因平台而异(它可以在 Unix 上如此使用;它不能在 Windows NT 或更高版本上)。”请注意,当您调用 command 时,使用 with 语句会使临时文件保持打开状态,因此您的代码的可移植性会受到影响。
    【解决方案2】:

    试试这个:

    import tempfile
    import commands
    import os
    
    commandname = "cat"
    
    f = tempfile.NamedTemporaryFile(delete=False)
    f.write("oh hello there")
    f.close() # file is not immediately deleted because we
              # used delete=False
    
    res = commands.getoutput("%s %s" % (commandname,f.name))
    print res
    os.unlink(f.name)
    

    它只是打印临时文件的内容,但这应该给你正确的想法。请注意,该文件在外部进程看到之前已关闭 (f.close())。这很重要——它确保您的所有写操作都被正确刷新(并且,在 Windows 中,您没有锁定文件)。 NamedTemporaryFile 实例通常一关闭就被删除;因此delete=False 位。

    如果您想对流程进行更多控制,可以尝试subprocess.Popen,但听起来commands.getoutput 可能足以满足您的目的。

    【讨论】:

    • 这个答案(尤其是delete=False & close())是 Windows 案例的关键信息。谢谢。
    【解决方案3】:

    如果您需要一个有名字的临时文件,您必须使用NamedTemporaryFile 函数。然后你可以使用temp.name。读 http://docs.python.org/library/tempfile.html了解详情。

    【讨论】:

    • @balki 或者你可以通过 bufsize=0 使其无缓冲。
    【解决方案4】:

    改用NamedTemporaryFile 及其成员name。由于Unix filesystems 的工作方式,普通的TemporaryFile 甚至不能保证有名字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多