1

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 here.

#!/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)
Community
  • 1
  • 1
rup
  • 961
  • 3
  • 12
  • 25

1 Answers1

11

You did not call close. Use fd.close() (you forgot the parentheses there to make it an actual function call). This could have been prevented by using the with-statement:

with open("__q", "w") as fd:
    fd.write(t)
# will automatically be closed here
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • I spent so much time trying to figure this out. Is there a way Python could have been made to detect this kind of syntax error? – rup Jun 02 '11 at 11:37