2016-07-16 40 views
2

我有一些代碼建立日誌在Python 2.7:記錄到蟒文件不使用模式時,「W」的參數(使用記錄模塊)改寫文件=到的FileHandler

import os 
import logging 
logger=logging.getLogger('CopasiTools') 
logger.setLevel(logging.DEBUG) 
log_filename=os.path.join(os.path.dirname(copasi_file),os.path.split(copasi_file)[1][:-4]+'_log.log') 
handler=logging.FileHandler(log_filename,mode='w') 
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") 
handler.setFormatter(formatter) 
logger.addHandler(handler) 
logger.debug('debugging message') 

這代碼的作品和我得到的輸出,但我打算,所以我想每次都覆蓋日誌文件,它的運行使用此日誌中做了很多的調試。在docs說使用mode關鍵字參數以「的FileHandler . It doesn't specify precisely *which* mode to use for overwrite file each time but I think a reasonable assumption would be模式=」 w'`。但是這不起作用。有人可以告訴我爲什麼嗎?

+0

我無法重現行爲。我使用了您提供的代碼,只是更改了文件名,每次運行代碼時都會覆蓋日誌。如果我將'mode'改爲'a',那麼新的運行會將行添加到末尾, – niemmi

+0

這很奇怪,可能與以前的[question]有關(http://stackoverflow.com/questions/38396050/why-does-this -code換創建-A-python的日誌 - 不工作?noredirect = 1個#comment64203174_38396050)我有。你知道是否有可能永久覆蓋日誌記錄模塊的基本行爲? – CiaranWelsh

+0

我不知道這樣做的方式,但這並不意味着這是不可能的, – niemmi

回答

1

問題是該文件實際上並沒有被覆蓋,直到一個新的python shell啓動。

0

我不熟悉這個樣,和我真的沒有看到任何在谷歌伸出。您是否嘗試過使用:

handler=logging.FileHandler(log_filename, 'w') 
+0

謝謝,但這表現方式相同。 – CiaranWelsh