简体   繁体   English

如何在Python中将日志写入字节或内存流?

[英]How to write a log to a byte or memory stream in Python?

I want to write a running log to some kind of memory or byte stream. 我想将运行日志写入某种内存或字节流。 For example, in C# or Java, there exists a memorystream object to accomplish this. 例如,在C#或Java中,存在一个memorystream对象来完成此任务。 Is there some way I can facilitate writing a log to memory in Python? 有什么办法可以帮助我在Python中将日志写入内存?

Instead of this: 代替这个:

file_handle = open("log.txt", "w")
# ...
if (some_error):
    file_handle.write("event 1:...")
    file_handle.write("event 2:...")
    # ...
file_handle.close()

I want to write a running log to some structure in memory. 我想将运行日志写入内存中的某些结构。 What is best practice for this in Python? 在Python中最佳做法是什么? A String object? 字符串对象? Something else? 还有吗

Thank you. 谢谢。

如果您正在寻找带有类似文件的接口的字符串,那么您需要的是StringIO

It looks like the StreamHandler class best describes what you are looking for. 看起来StreamHandler类最好地描述了您要寻找的内容。

"The StreamHandler class, located in the core logging package, sends logging output to streams such as sys.stdout, sys.stderr or any file-like object (or, more precisely, any object which supports write() and flush() methods)." “位于核心日志记录包中的StreamHandler类将日志记录输出发送到流,例如sys.stdout,sys.stderr或任何类似文件的对象(或更确切地说,是任何支持write()和flush()方法的对象)。”

And this HOWTO describes logging in python in detail. 并且此HOWTO详细描述了python登录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM