如何在搭载R内核的Jupyter Notebook中捕获STDERR输出
在R内核的Jupyter Notebook中捕获STDERR输出的方法
问题描述
使用R内核(IRkernel)的Jupyter Notebook中,STDERR输出无法在界面显示,仅会出现在运行Jupyter服务器的后台终端中。示例代码及现象如下:
Notebook单元格代码:
cat("O kay!", file = stdout()) # 预期输出:O kay! cat("Oh no!", file = stderr()) # 实际无输出,但后台终端会显示"Oh no!"
后台终端输出片段:
[I 2025-01-25 23:04:35.005 ServerApp] Kernel started: 160c6e0c-54fc-4add-b5b7-9239fc9209bc [I 2025-01-25 23:04:35.879 ServerApp] Connecting to kernel 160c6e0c-54fc-4add-b5b7-9239fc9209bc. Oh no!
会话信息:
- R: 4.4.0
- IRkernel (R包): 1.3.2
- Python: 3.12.3
- IPython: 8.26.0
- ipykernel: 6.29.4
- ipywidgets: 8.1.2
- jupyter_client: 8.6.3
- jupyter_core: 5.7.2
- jupyter_server: 2.14.0
- jupyterlab: 4.3.4
- nbclient: 0.10.0
- nbconvert: 7.16.4
- nbformat: 5.10.4
- notebook: 7.2.0
- qtconsole: 5.6.0
- traitlets: 5.14.3
解决方案
可以通过以下三种方法在Notebook界面中捕获并显示STDERR输出:
方法1:临时重定向STDERR到STDOUT
使用R的sink()函数临时将错误流重定向到标准输出,输出即可显示在单元格中:
# 重定向STDERR到STDOUT sink(stdout(), type = "message") cat("Oh no!", file = stderr()) # 此时Notebook单元格会输出"Oh no!" # 恢复默认输出配置 sink(type = "message")
方法2:捕获STDERR输出到变量
使用capture.output()函数指定type = "message"参数,捕获STDERR内容后再打印:
# 捕获STDERR输出 err_content <- capture.output(cat("Oh no!", file = stderr()), type = "message") # 打印捕获的内容 print(err_content) # 输出:[1] "Oh no!"
方法3:全局配置IRkernel自动重定向
若希望所有R内核会话自动显示STDERR,可修改IRkernel的配置文件:
- 定位IRkernel配置目录:
- Linux/macOS:
~/.ipython/kernels/ir/ - Windows:
%APPDATA%\jupyter\kernels\ir\
- Linux/macOS:
- 编辑
kernel.json文件,在argv列表中添加--redirect-stderr-to-stdout参数,修改后示例:
{ "argv": [ "R", "--slave", "--no-restore", "--redirect-stderr-to-stdout", "-e", "IRkernel::main()" ], "display_name": "R", "language": "r" }
- 重启Jupyter服务器,之后所有R内核的Notebook都会自动在界面显示STDERR输出。
内容的提问来源于stack exchange,提问作者foehn
相关产品推荐
相关产品推荐

