In a Python program, why can't I cat a file right after writing it?
在创建和写入文件之后,我就尝试使用popen()对其进行cat。它不起作用。print p给出两个空元组("",""。为什么?正如这里讨论的,我使用重命名来确保原子写入。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #!/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) |
你没有打电话给
1 2 3 | with open("__q","w") as fd: fd.write(t) # will automatically be closed here |