How to redirect stderr in Python?

前端 未结 10 958
暖寄归人
暖寄归人 2020-11-27 06:19

I would like to log all the output of a Python script. I tried:

import sys

log = []

class writer(object):
    def write(self, data):
        log.append(dat         


        
10条回答
  •  独厮守ぢ
    2020-11-27 07:13

    I found this approach to redirecting stderr particularly helpful. Essentially, it is necessary to understand if your output is stdout or stderr. The difference? Stdout is any output posted by a shell command (think an 'ls' list) while sterr is any error output.

    It may be that you want to take a shell commands output and redirect it to a log file only if it is normal output. Using ls as an example here, with an all files flag:

    # Imports
    import sys
    import subprocess
    
    # Open file
    log = open("output.txt", "w+")
    
    # Declare command
    cmd = 'ls -a'
    # Run shell command piping to stdout
    result = subprocess.run(cmd, stdout=subprocess.PIPE, shell=True)
    # Assuming utf-8 encoding
    txt = result.stdout.decode('utf-8')
    # Write and close file
    log.write(txt)
    log.close()
    

    If you wanted to make this an error log, you could do the same with stderr. It's exactly the same code as stdout with stderr in its place. This pipes an error messages that get sent to the console to the log. Doing so actually keeps it from flooding your terminal window as well!

    Saw this was a post from a while ago, but figured this could save someone some time :)

提交回复
热议问题