create & read from tempfile

前端 未结 4 1868
难免孤独
难免孤独 2020-12-09 01:17

Is there anyway I could write to tempfile and include it in a command, and then close/remove it. I would like to execute the command, eg: some_command /tmp/some-temp-file.

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 01:50

    Try this:

    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)
    

    It just prints the content of the temp file, but that should give you the right idea. Note that the file is closed (f.close()) before the external process gets to see it. That's important -- it ensures that all your write ops are properly flushed (and, in Windows, that you're not locking the file). NamedTemporaryFile instances are usually deleted as soon as they are closed; hence the delete=False bit.

    If you want more control over the process, you could try subprocess.Popen, but it sounds like commands.getoutput may be sufficient for your purposes.

提交回复
热议问题