Suppress stdout / stderr print from Python functions

前端 未结 9 1856
情歌与酒
情歌与酒 2020-11-29 06:59

I have a Python script that is using some closed-box Python functions (i.e. I can\'t edit these functions) provided by my employer. When I call these functions, they are pri

相关标签:
9条回答
  • 2020-11-29 07:48

    If you are running this script on a linux based machine, you should be able to:

    $> ./runscript.py > output.txt
    
    0 讨论(0)
  • 2020-11-29 07:50

    python 3.6 working version, tested with million suppressions without any errors

    import os
    import sys
    
    class suppress_stdout_stderr(object):
        def __enter__(self):
            self.outnull_file = open(os.devnull, 'w')
            self.errnull_file = open(os.devnull, 'w')
    
            self.old_stdout_fileno_undup    = sys.stdout.fileno()
            self.old_stderr_fileno_undup    = sys.stderr.fileno()
    
            self.old_stdout_fileno = os.dup ( sys.stdout.fileno() )
            self.old_stderr_fileno = os.dup ( sys.stderr.fileno() )
    
            self.old_stdout = sys.stdout
            self.old_stderr = sys.stderr
    
            os.dup2 ( self.outnull_file.fileno(), self.old_stdout_fileno_undup )
            os.dup2 ( self.errnull_file.fileno(), self.old_stderr_fileno_undup )
    
            sys.stdout = self.outnull_file        
            sys.stderr = self.errnull_file
            return self
    
        def __exit__(self, *_):        
            sys.stdout = self.old_stdout
            sys.stderr = self.old_stderr
    
            os.dup2 ( self.old_stdout_fileno, self.old_stdout_fileno_undup )
            os.dup2 ( self.old_stderr_fileno, self.old_stderr_fileno_undup )
    
            os.close ( self.old_stdout_fileno )
            os.close ( self.old_stderr_fileno )
    
            self.outnull_file.close()
            self.errnull_file.close()
    
    0 讨论(0)
  • 2020-11-29 07:52

    This approach (found through the related sidebar) might work. It reassigns the file descriptors rather than just the wrappers to them in sys.stdout, etc.

    0 讨论(0)
提交回复
热议问题