简体   繁体   English

Python stdout 和 stdout.buffer 捕获

[英]Python stdout and stdout.buffer capture

Hey i want to prevent any stdouts from anywhere and capture it in a variable.嘿,我想防止来自任何地方的任何标准输出并将其捕获在变量中。

Now the problem:现在的问题:

I have two methods to print something in stdout我有两种方法可以在标准输出中打印一些东西

Method 1:方法一:

print("Normal Print")

Method 2:方法二:

fds: List[BinaryIO] = [sys.stdin.buffer, sys.stdout.buffer, sys.stderr.buffer]
fds[1].write(b"%d\n" % a)
fds[1].flush()

Now i tried something like this现在我尝试了这样的事情

from io import BufferedWriter, BytesIO, StringIO

mystdout = StringIO()
mystdout.buffer = BufferedWriter(raw=BytesIO())
sys.stdout = mystdout

But with this i get no output at all.但是有了这个,我根本没有输出。

How is the best way to archiev this?归档此文件的最佳方法是什么?

What do you mean that you get no output at all?你的意思是你根本没有输出? It's in variable:它在变量中:

mystdout = StringIO()
mystdout.buffer = BufferedRandom(raw=BytesIO()) # You can read from BufferedRandom
sys.stdout = mystdout
sys.stdout.buffer.write(b"BUFFER")
print("PRINT")
sys.stdout = sys.__stdout__ # Restore original stdout

print(mystdout.getvalue()) # PRINT
mystdout.buffer.seek(0)
print(mystdout.buffer.read()) b"BUFFER"

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

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