PyAudio 警告污染输出

PyAudio warnings poluting output

我有这个程序可以听麦克风并尝试识别所说的内容:

#!/usr/bin/env python3

import speech_recognition

recognizer = speech_recognition.Recognizer()

class Recognition:

    def __init__(self):
        self.recognizer = speech_recognition.Recognizer()

    def listen(self):
        with speech_recognition.Microphone() as source:
            self.recognizer.adjust_for_ambient_noise(source)
            self.audio = self.recognizer.listen(source)

    def recognize_sphinx(self):
        decoder = self.recognizer.recognize_sphinx(self.audio, show_all=True)
        for best, i in zip(decoder.nbest(), range(10)):
            return best.hypstr


r = Recognition()
r.listen()
print(r.recognize_sphinx())

尽管代码有效,但它会在输出中显示以下警告:

ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2266:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map
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
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
JackShmReadWritePtr::~JackShmReadWritePtr - Init not done for 4294967295, skipping unlock
potato

问题是我想要一个脚本来执行上面的代码并读取它的输出(马铃薯),但是返回的结果与所有这些错误混合在一起。我尝试了我看到的解决方案 here,但它只会抑制 alsa 警告。可能弄乱 alsa/pulseaudio 配置会解决这个问题,但我不想在每台运行代码的机器上都这样做。

我也尝试将 stdin/stderr 重定向到 null,但没有抑制任何内容。

我有一个解决方法,即当脚本运行该程序时,只获取最后一行,但我只想将其作为最后一个资源。

warning/status 消息转到标准错误输出 (stderr),而 print() 调用的输出转到标准输出 (stdout)。 将两者分开应该是微不足道的。

如果您想真正抑制 warning/status 消息,您可以查看 my answer to the SO-question you were mentioning, or 我从那里链接到的内容。