在Python中,如何抑制选择代码的控制台输出?

时间:2016-04-28 10:34:10

标签: python stdout stderr pyaudio silent

我有一小部分代码:

stream = pyaudio.PyAudio().open(
    format   = pyaudio.PyAudio().get_format_from_width(1),
    channels = 1, 
    rate     = bitrate, 
    output   = True
)

当我运行它时,会产生几行控制台输出:

ALSA lib pcm_dsnoop.c:614:(snd_pcm_dsnoop_open) unable to open slave
ALSA lib pcm_dmix.c:1024:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm.c:2267:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2267:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2267:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_dmix.c:1024:(snd_pcm_dmix_open) unable to open slave
Cannot connect to server socket err = No such file or directory
Cannot connect to server request channel
jack server is not running or cannot be started

如何在不使其他代码的控制台输出消失的情况下更改围绕此特定函数调用的代码以使上述表单的控制台输出不显示?

我正在以上下文管理器的形式想象一个解决方案,可能有点像下面的内容:

@contextlib.contextmanager
def silence():
    # <insert magic to direct stdout and stderr to null>
    yield
    # <insert magic to direct stdout and stderr to console>

with silence():
    stream = pyaudio.PyAudio().open(
        format   = pyaudio.PyAudio().get_format_from_width(1),
        channels = 1, 
        rate     = bitrate, 
        output   = True
    )

1 个答案:

答案 0 :(得分:0)

装饰师可以工作。也许是这样的:

def silence(func):
    def silenced():
        // silence output
        func()
        // change output to normal
    return silenced


@silence
def openStream(args):
    stream = pyaudio.PyAudio().open(
        format   = pyaudio.PyAudio().get_format_from_width(1),
        channels = 1, 
        rate     = bitrate, 
        output   = True
    )
    return stream