How to duplicate sys.stdout to a log file?

前端 未结 17 902
醉酒成梦
醉酒成梦 2020-11-22 06:54

Edit: Since it appears that there\'s either no solution, or I\'m doing something so non-standard that nobody knows - I\'ll revise my question to also ask: What is the best w

17条回答
  •  渐次进展
    2020-11-22 07:46

    If you wish to log all output to a file AND output it to a text file then you can do the following. It's a bit hacky but it works:

    import logging
    debug = input("Debug or not")
    if debug == "1":
        logging.basicConfig(level=logging.DEBUG, filename='./OUT.txt')
        old_print = print
        def print(string):
            old_print(string)
            logging.info(string)
    print("OMG it works!")
    

    EDIT: Note that this does not log errors unless you redirect sys.stderr to sys.stdout

    EDIT2: A second issue is that you have to pass 1 argument unlike with the builtin function.

    EDIT3: See the code before to write stdin and stdout to console and file with stderr only going to file

    import logging, sys
    debug = input("Debug or not")
    if debug == "1":
        old_input = input
        sys.stderr.write = logging.info
        def input(string=""):
            string_in = old_input(string)
            logging.info("STRING IN " + string_in)
            return string_in
        logging.basicConfig(level=logging.DEBUG, filename='./OUT.txt')
        old_print = print
        def print(string="", string2=""):
            old_print(string, string2)
            logging.info(string)
            logging.info(string2)
    print("OMG")
    b = input()
    print(a) ## Deliberate error for testing
    

提交回复
热议问题