PyAudio warnings poluting output

☆樱花仙子☆ 提交于 2021-01-29 03:29:35

问题


I have this program that listens to the microphone and tries to recognize what was said:

#!/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())

Although the code works, it does display the following warnings along with the output:

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

The problem is I want a script to execute the code above and read its output (potato), but the returned result is mixed with all those errors. I tried the solution I saw here, but it only suppress the alsa warnings. Probably messing with alsa/pulseaudio configs will solve this problem, but I don't want to do that on every machine that runs the code.

I also tried redirecting stdin/stderr to null, but didn't suppress anything.

I have a workaround in mind that is, when the script runs this program, to get only the last line, but I want that only as a last resource.


回答1:


The warning/status messages go to the standard error output (stderr), while the output of your print() call goes to the standard output (stdout). It should be trivial to separate the two.

If you want to actually suppress the warning/status messages, you can have a look at my answer to the SO-question you were mentioning, or the more verbose answer I've linked to from there.



来源:https://stackoverflow.com/questions/37733318/pyaudio-warnings-poluting-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!