2011-05-19 72 views
1

我想創建一個測試控制器,並希望測試的執行被收集到一個文件。如何創建測試執行的日誌文件

我知道使用,三通和重定向測試腳本執行到某個文件,但我有興趣與蟒蛇在linux下做到這一點。

所以,每當執行測試時,應該得到創建的日誌文件,所有的執行日誌,包括標準輸入,輸出和錯誤應該得到收集到這個文件這種情況。

請求某些機構建議我,如何實現這種想法!

感謝 的OpenFile

+0

如果你不想「重新發明輪子」有[現有框架](http://code.google.com/p/pycopia/)已經這樣做了,還有更多(無恥插件)。 – Keith 2011-05-19 06:55:57

回答

2

打開並寫入文件:

mylogfile = 'bla.log' 
f = open(mylogfile, 'a') 
f.write('i am logging! logging logging!....loggin? timber!....') 
f.close() 

看在根目錄下有腳本 'bla.log' 和讀取,享受

+2

它覆蓋文件,如果你用'w'打開它。 – bfontaine 2011-05-19 06:21:34

2

您可以編寫一個函數像這樣:

def writeInLog(msg): 
    with open("log", "a") as f: 
     f.write(msg+"\n") 

它會打開文件「日誌「,然後附加(」a「)消息後跟一個換行符,然後關閉該文件。

0
# Save the current stream 
saveout = sys.stdout 


f = "a_log_file.log" 
fsock = open(f, 'w') 

# Set stream to file 
sys.stdout = fsock 

### 
# do something here 
# any print function will send the stream to file f 
### 

# Reset back the stream to what it was 
sys.stdout = saveout 
fsock.close() 
3

試試這個:

import sys 

# Save the current stream 
save_out = sys.stdout 

# Define the log file 
f = "a_log_file.log" 
# Append to existing log file. 
# Change 'a' to 'w' to recreate the log file each time. 
fsock = open(f, 'a') 

# Set stream to file 
sys.stdout = fsock 

### 
# do something here 
# any print function calls will send the stream to file f 
### 

# Reset back the stream to what it was 
# any print function calls will send the stream to the previous stream 
sys.stdout = save_out 
fsock.close() 
5

有幾個很好的日誌記錄模塊,從內置的logging,這裏是official cookbook。比較有趣的第三方庫是Logbook,這裏是一個相當裸例子只是皮毛其very cool features的表面:

import logbook 

def f(i,j): 
    return i+j 

logger = logbook.Logger('my application logger') 
log = logbook.FileHandler('so.log') 
log.push_application() 

try: 
    f(1, '2') 
    logger.info('called '+f.__name__) 
except: 
    logger.warn('failed on ') 


try: 
    f(1, 2) 
    logger.info('called '+f.__name__) 
except: 
    logger.warn('choked on, ') 

so.log則是這樣的:

[2011-05-19 07:40] WARNING: my application logger: failed on 
[2011-05-19 07:40] INFO: my application logger: called f