如何将stderr导向我的StreamWriter对象?

huangapple go评论59阅读模式
英文:

How to pipe stderr to my StreamWriter object?

问题

我有一个类型为 StreamWriter 的对象。如何将 stderr 管道传输到它?

在 Node 中,我会像这样做:stderr.pipe(my_stream)

英文:

I have an object of type StreamWriter. How can I pipe stderr to it?
In Node i would do something like: stderr.pipe(my_stream).

答案1

得分: 2

在Python中,您可以简单地将您的流分配为sys.stderr

import sys

my_stream = StreamWriter()

sys.stderr = my_stream

尽管如此,使用contextlib的redirect_stderr函数可能更易于管理,因为它只会暂时将流重定向到stderr。

from contextlib import redirect_stderr

my_stream = StreamWriter()

with redirect_stderr(my_stream):
    # 在此块内,所有stderr的输出都将重定向到my_stream
英文:

In Python, you can simply assign your stream as sys.stderr.

import sys

my_stream = StreamWriter()

sys.stderr = my_stream

Although, using contextlib's redirect_stderr function can be more manageable as it only temporarily redirects a stream to stderr.

from contextlib import redirect_stderr

my_stream = StreamWriter()

with redirect_stderr(my_stream):
    # Any output to stderr will be redirected to my_stream within this block

huangapple
  • 本文由 发表于 2023年7月3日 22:20:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76605635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定