在Python程序中,为什么我不能在编写文件后立即捕获文件?

rup*_*rup 1 python

在创建和写入之后,我尝试使用Popen()捕获文件.它不起作用.Print p给出两个空元组('','').为什么?我用的重命名,以确保原子写入,为讨论在这里.

#!/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)
Run Code Online (Sandbox Code Playgroud)

Bjö*_*lex 11

你没有打电话close.使用fd.close()(你忘了那里的括号使它成为一个实际的函数调用).这可以通过使用with-statement 来防止:

with open("__q", "w") as fd:
    fd.write(t)
# will automatically be closed here
Run Code Online (Sandbox Code Playgroud)