当前位置:网站首页>Jupyter notebook solves the problem that printing information cannot be viewed after closing the browser

Jupyter notebook solves the problem that printing information cannot be viewed after closing the browser

2022-07-27 23:01:00 Go crazy first.

One 、 Problem description

In the browser, we close the model we are training after printing , Open it again and you can see that there is no information output . In addition to handling cache methods , We can use python Of logging Output log .

Two 、 Code writing

import logging
import sys
import datetime

def init_logger(filename, logger_name):
    '''
    @brief:
        initialize logger that redirect info to a file just in case we lost connection to the notebook
    @params:
        filename: to which file should we log all the info
        logger_name: an alias to the logger
    '''

    # get current timestamp
    timestamp = datetime.datetime.utcnow().strftime('%Y%m%d_%H-%M-%S')
    
    logging.basicConfig(
        level=logging.INFO, 
        format='[%(asctime)s] %(name)s {%(filename)s:%(lineno)d} %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(filename=filename),
            logging.StreamHandler(sys.stdout)
        ]
    )

    # Test
    logger = logging.getLogger(logger_name)
    logger.info('### Init. Logger {} ###'.format(logger_name))
    return logger

# Initialize
my_logger = init_logger("./ml_notebook.log", "ml_logger")

Print out each time, such as :

my_logger.info("XXX")

Another example is to record the last cell Time and output of , Print to the log file , For example, in the first cell in :

%%capture out
%%timeit
a = 1+1

  And then next cell in :

my_logger.info("capture & timeit: " + out.stdout)

You can know the last cell Running time and content .

Reference resources :

jupyter notebook How to execute and save the results in the background after closing the browser ? - You know (zhihu.com)

logging — Logging facility for Python — Python 3.10.5 documentation

原网站

版权声明
本文为[Go crazy first.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/198/202207141613226648.html