2011-05-31 31 views
1

我試圖在創建並寫入文件之後使用Popen()創建一個文件。它不起作用。打印p給出兩個空元組('','')。爲什麼?我已經使用重命名來確保原子寫入,如討論here在Python程序中,爲什麼我不能在寫入文件後立即捕捉文件?

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

附加殼=真在你subprocess.Popen()方法 – 2011-05-31 10:42:09

回答

11

您沒有撥打close。使用fd.close()(您忘記了那裏的括號以使其成爲實際的函數調用)。這本來是可以避免使用with語句來:

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

我花了這麼多時間試圖弄清楚這一點。有沒有辦法使用Python來檢測這種語法錯誤? – rup 2011-06-02 11:37:13

相關問題