Suppressing output of module calling outside library

后端 未结 4 2127
花落未央
花落未央 2020-12-02 00:01

I have an annoying problem when using machine learning library PyML. PyML uses libsvm to train the SVM classifier. The problem is that libsvm outputs some text to standard o

4条回答
  •  不知归路
    2020-12-02 01:03

    I had a similar problem with portaudio/PyAudio initialization. I started with Reid's answer, which worked. Although I needed to redirect stderr instead. So, here is an updated, cross-platform version that redirects both:

    import sys, os
    
    # hide diagnostic output
    with open(os.devnull, 'w') as devnull:
        # suppress stdout
        orig_stdout_fno = os.dup(sys.stdout.fileno())
        os.dup2(devnull.fileno(), 1)
        # suppress stderr
        orig_stderr_fno = os.dup(sys.stderr.fileno())
        os.dup2(devnull.fileno(), 2)
    
        print('*** stdout should be hidden!  ****')
        print('*** stderr should be too!  ****',
              file=sys.stderr)
    
        os.dup2(orig_stdout_fno, 1)  # restore stdout
        os.dup2(orig_stderr_fno, 2)  # restore stderr
    
    print('done.')
    

    Should be easy to comment out a part you don't need.

提交回复
热议问题