我正在编写一个开发人员工具,其中一部分将在后台启动Jupyter笔记本,并将输出发送到特定文件,例如
jupyter notebook --ip 0.0.0.0 --no-browser --allow-root
>> ${NOTEBOOK_LOGFILE} 2>&1 &
但是,我仍然希望通过标准输出将笔记本的启动信息打印到控制台。如
[I 18:25:33.166 NotebookApp] Writing notebook server cookie secret to /root/.local/share/jupyter/runtime/notebook_cookie_secret
[I 18:25:33.189 NotebookApp] Serving notebooks from local directory: /faces
[I 18:25:33.189 NotebookApp] 0 active kernels
[I 18:25:33.189 NotebookApp] The Jupyter Notebook is running at: http://0.0.0.0:8888/?token=b02f25972...
[I 18:25:33.189 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 18:25:33.189 NotebookApp]
Copy/paste this URL into your browser when you connect for the first time,
to login with a token:
http://0.0.0.0:8888/?token=b02f25972...
以便用户仍可以看到他们需要的 URL 连接字符串。
我试图在笔记本命令之后cat
这个文件,但这有一些缺点。
笔记本启动和打印消息所需的时间是可变的,并且不希望结合使用sleep
和日志文件cat
,因为如果启动时间出现罕见的延迟,则日志文件cat
可能不打印任何内容,因为该文件为空。
另一方面,我不想将睡眠时间设置为过高的数字,因为这样用户将不得不在启动时等待太长时间。
我也尝试过tail -f ${NOTEBOOK_LOGFILE} | grep -n 10
(因为启动线将是前 10 条(。这是有希望的,但是笔记本服务器不会在每一行附加换行符,直到下一行传入。这意味着,如果您等待 10 行,tail
进程将挂起,直到将其他消息记录到日志文件(生成第 10 个换行符(。
如何确保从笔记本输出启动信息时起及时向 stdout 显示启动信息,同时仍将笔记本输出重定向到日志文件中?
我想了一个技巧来用tail
和head
来做到这一点,但会对更简单的东西感兴趣。
(tail -f -n +1 ${NOTEBOOK_LOGFILE} | head -n 5);
这依赖于连接 URL 也打印在前 5 行之间的事实,因此如果您尝试从第 9 行和第 10 行中提取它,缺少让head
等待的换行符无关紧要。