Directing print output to a .txt file

后端 未结 7 2471
北荒
北荒 2020-11-27 13:03

Is there a way to save all of the print output to a txt file in python? Lets say I have the these two lines in my code and I want to save the print output to a file named

7条回答
  •  一整个雨季
    2020-11-27 13:22

    Use the logging module

    def init_logging():
        rootLogger = logging.getLogger('my_logger')
    
        LOG_DIR = os.getcwd() + '/' + 'logs'
        if not os.path.exists(LOG_DIR):
            os.makedirs(LOG_DIR)
        fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
        rootLogger.addHandler(fileHandler)
    
        rootLogger.setLevel(logging.DEBUG)
    
        consoleHandler = logging.StreamHandler()
        rootLogger.addHandler(consoleHandler)
    
        return rootLogger
    

    Get the logger:

    logger = init_logging()
    

    And start logging/output(ing):

    logger.debug('Hi! :)')
    

提交回复
热议问题