In a Python program, why can't I cat a file right after writing it?
<p>I tried to cat a file, using Popen(), right after creating and writing to it. It doesn't work. Print p gives two empty tuples ('',''). Why ? I've used rename to ensure an atomic write, as discussed <a href="http://stackoverflow.com/questions/2333872/atomic-writing-to-file-with-python">here</a>.</p>

<pre><code>#!/usr/bin/env python
import sys,os,subprocess

def run(cmd):
    try:
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        p.wait()
        if p.returncode:
            print "failed with code: %s" % str(p.returncode)
        return p.communicate()
    except OSError:
        print "OSError"

def main(argv):
    t = "alice in wonderland"
    fd = open("__q", "w"); fd.write(t); fd.close; os.rename("__q","_q")
    p = run(["cat", "_q"])
    print p

main(sys.argv)
</code></pre>
