jupyter notebook,如何在关闭浏览器之后程序继续执行

发布时间 2023-10-08 09:35:43作者: emanlee

 

关于关闭浏览器选项卡后保持 Jupyter notebook 运行

最简单的解决方法似乎是 内置单元魔法 %%capture:

%%capture output
# Time-consuming code here

保存,关闭标签,稍后回来.输出现在存储在 output 变量中:

output.show()

这将显示所有临时print结果以及普通或丰富的输出单元格.

=========================================

Anything already running in the
notebook will keep running, and the kernel it started for that will
stay running - so it won't lose your variables. However, any output
produced while the notebook isn't open in a browser tab is lost; there
isn't an easy way to change this until we have the notebook server
able to track the document state, which has been on the plan for ages.

=========================================

先说一下后台执行的问题。后台跑上 jupyter notebook 的话,会自动打开浏览器,但关掉浏览器的话进程不会结束,已经在运行的 notebook 和里面的 cell 还会继续运行。毕竟很多时候在没有屏幕的服务器上我们都是用无浏览器的模式跑 jupyter notebook 的。

# 无浏览器模式,想要打开 notebook 就直接在浏览器里输入 localhost:8888 就可以了
$ jupyter notebook --no-browser

比如一不小心关掉了浏览器,想要重新在浏览器里打开 notebook 的话,就在浏览器里打开 localhost:8888 就好了(8888 是 jupyter notebook 的默认端口)。

当然如果这样打开之前还在运行的 notebook 的话,就看不到里面正在运行的 cell 打印的最新的结果了,所以我们需要保存结果。

可以考虑用 python 的 logging,可以把你想要打印的都写在一个日志文件

里,这样你关掉浏览器也没关系了。

 

代码的话比如这样:

作者:YAOJ
链接:https://www.zhihu.com/question/308665219/answer/1699640781
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

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")

这样就可以在每一次训练结束的时候,把训练结果用 (“...”)打印到当前路径下的 ml_notebook.log 的文件里了,每一行还会标好这一行打印的时间,也就是上面 logging.basicConfig 里 format 定义的格式。当然你也可以自己定义自己习惯的格式。

配合 jupyter notebook 的 magic command,还可以把每个 cell 运行的时间记录并且打印到日志文件里。比如在第一个 cell 里:

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

然后在下一个 cell 里:

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

就能知道上一个 cell 运行了多久了。

更多 logging 的用法可以参考官方文档[1]

参考

  1. ^Python - logging https://docs.python.org/3/library/logging.html

 链接:https://www.zhihu.com/question/308665219/answer/1699640781

 

=========================================

 

REF

https://www.it1352.com/2751495.html

https://www.codenong.com/43628544/