简体   繁体   English

在 Python 程序中,为什么我不能在写入文件后立即 cat 文件?

[英]In a Python program, why can't I cat a file right after writing it?

I tried to cat a file, using Popen(), right after creating and writing to it.在创建并写入文件后,我尝试使用 Popen() 对文件进行分类。 It doesn't work.它不起作用。 Print p gives two empty tuples ('','').打印 p 给出两个空元组 ('','')。 Why?为什么? I've used rename to ensure an atomic write, as discussed here .我已经使用 rename 来确保原子写入,如此所述。

#!/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)

You did not call close .你没有打电话close Use fd.close() (you forgot the parentheses there to make it an actual function call).使用fd.close() (您忘记了那里的括号以使其成为实际的 function 调用)。 This could have been prevented by using the with -statement:这可以通过使用with语句来防止:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM