Suppressing output of module calling outside library

后端 未结 4 2124
花落未央
花落未央 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 00:48

    Dave Smith gave a wonderful answer to that on his blog. Basically, it wraps Ignacio's answer nicely:

    def suppress_stdout():
        with open(os.devnull, "w") as devnull:
            old_stdout = sys.stdout
            sys.stdout = devnull
            try:  
                yield
            finally:
                sys.stdout = old_stdout
    

    Now, you can surround any function that garbles unwanted noise into stdout like this:

    print "You can see this"
    with suppress_stdout():
        print "You cannot see this"
    print "And you can see this again"
    

    For Python 3 you can use:

    from contextlib import contextmanager
    import os
    import sys
    
    @contextmanager
    def suppress_stdout():
        with open(os.devnull, "w") as devnull:
            old_stdout = sys.stdout
            sys.stdout = devnull
            try:  
                yield
            finally:
                sys.stdout = old_stdout
    

提交回复
热议问题