2011-05-19 57 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