【发布时间】:2014-10-31 18:54:09
【问题描述】:
所以我正在尝试编写一个装饰器来记录标准输出,同时打印它。重点是分叉输出,以便它显示在控制台中,并被记录下来。这就是我目前所拥有的:
from time import time
import tempfile
import sys
import datetime
def printUsingTempFile(f):
def wrapper(*a, **ka):
with open('sysLog.txt', 'a') as logFile:
with tempfile.NamedTemporaryFile() as f:
sys.stdout = f
sys.stderr = f
retVal = f(*a, **ka)
f.flush(); f.seek(0); logFile.write('\n'.join(f.readlines()))
f.flush(); f.seek(0); sys.__stdout__.write('\n'.join(f.readlines()))
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
return retVal
return wrapper
if __name__ == '__main__':
@printUsingTempFile
def someFunc(abc='Hello!!!'):
'''
This is the docstring of the someFunc function.
'''
print abc
return 1
someFunc('Print something here')
我是这样运行的:
In [18]: !python utility.py
因为如果我使用 run 函数运行,愚蠢的 iPython 窗口会关闭。
我在目录中得到一个名为'sysLog.txt' 的新文件,但它是空的。也没有任何输出可见。没有错误或任何东西。根本不值一提!对此感到有些沮丧。不知道如何调试这段代码:(
编辑:
我意识到我没有寻找两次,所以我更新了代码。我尝试了以下代码:
def printUsingTempFile1():
with open('sysLog.txt', 'a') as logFile:
with tempfile.NamedTemporaryFile() as f:
sys.stdout = f
sys.stderr = f
print 'This is something ...'
f.flush(); f.seek(0); logFile.write('\n'.join(f.readlines()))
f.flush(); f.seek(0); sys.__stdout__.write('\n'.join(f.readlines()))
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
而且这个功能似乎工作正常。
【问题讨论】:
-
不要写入文件并从中读取,而是通过创建您自己的
LoggingWriter来反转该过程,其中write(self, value)方法将写入原始stdout和您的记录器。 -
现在工作。感谢桑杰。
-
重点是,写入文件并回读非常浪费资源;)
-
@Wolph 我想我明白你在说什么。听起来很有趣。我也试试。谢谢!
-
您可能还想研究使用 python 日志记录模块,您可以在其中将其配置为记录到控制台、文件等等。
标签: python decorator output-redirect