Ser*_*ens 58
使用日志记录模块(http://docs.python.org/library/logging.html):
import logging
logger = logging.getLogger('scope.name')
file_log_handler = logging.FileHandler('logfile.log')
logger.addHandler(file_log_handler)
stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)
# nice output format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
stderr_log_handler.setFormatter(formatter)
logger.info('Info message')
logger.error('Error message')
Run Code Online (Sandbox Code Playgroud)
Ult*_*nct 38
我想出了这个[未经测试]
import sys
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush() # If you want the output to be visible immediately
def flush(self) :
for f in self.files:
f.flush()
f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test" # This will go to stdout and the file out.txt
#use the original
sys.stdout = original
print "This won't appear on file" # Only on stdout
f.close()
Run Code Online (Sandbox Code Playgroud)
print>>xyz在python中期望一个write()函数xyz.您可以使用自己的自定义对象.或者,您也可以让sys.stdout引用您的对象,在这种情况下即使没有它也将进行编辑>>xyz.
我只想建立在Serpens的答案并添加一行:
logger.setLevel('DEBUG')
Run Code Online (Sandbox Code Playgroud)
这将允许您选择记录的消息级别.
例如,在Serpens示例中,
logger.info('Info message')
Run Code Online (Sandbox Code Playgroud)
不会被记录,因为它默认只记录警告及以上.
有关所用级别的更多信息,请参阅此处
可能是最短的解决方案:
def printLog(*args, **kwargs):
print(*args, **kwargs)
with open('output.out','a') as file:
print(*args, **kwargs, file=file)
printLog('hello world')
Run Code Online (Sandbox Code Playgroud)
向sys.stdout和写入“hello world” ,其output.out工作方式与 print() 完全相同。
Note:
Please do not specify the file argument for the printLog function. Calls like printLog('test',file='output2.out') are not supported.
这是对 @UltraInstinct 的 Tee 类的一个小改进,修改为上下文管理器并捕获任何异常。
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
要使用上下文管理器:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")
Run Code Online (Sandbox Code Playgroud)