How to redirect stderr in Python?

前端 未结 10 988
暖寄归人
暖寄归人 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:00

    To add to Ned's answer, it is difficult to capture the errors on the fly during the compilation.

    You can write several print statements in your script and you can stdout to a file, it will stop writing to the file when the error occurs. To debug the code you could check the last logged output and check your script after that point.


    Something like this:

    # Add to the beginning of the script execution(eg: if __name__ == "__main__":).
    from datetime import datetime
    dt = datetime.now()
    script_dir = os.path.dirname(os.path.abspath(__file__))      # gets the path of the script
    stdout_file = script_dir+r'\logs\log'+('').join(str(dt.date()).split("-"))+r'.log'
    sys.stdout = open(stdout_file, 'w')
    

    This will create a log file and stream the print statements to the file.


    Note: Watch out for escape characters in your filepath while concatenating with script_dir in the second line from the last in the code. You might want something similar to raw string. You can check this thread for this.

提交回复
热议问题