简体   繁体   English

如何将Jupyter Notebook单元中的错误保存到文件中?

[英]How to save errors from Jupyter Notebook cells to a file?

I am trying to save all output (stdout and all errors) of a cell to a file. 我正在尝试将单元格的所有输出(stdout和所有错误)保存到文件中。 To save stdout, I am using the following: 为了保存标准输出,我使用以下命令:

import sys
old_stdout = sys.stdout
sys.stdout = open('test.txt', 'w')
print("Hello World! ")

In this case, the output is not displayed and gets saved in the file as expected. 在这种情况下,不显示输出,而是按预期将其保存在文件中。 To save errors, I used: 为了节省错误,我使用了:

#Doesn't work
sys.stderr = open('error.txt','w')
print(a) #Should raise NameError

When I run this cell, I get the error in the notebook, and not in the file as expected: 运行此单元格时,在笔记本中出现错误,而不是在文件中出现错误:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-de3efd936845> in <module>()
      1 #Doesn't work
----> 2 sys.stderr = open('error.txt','w')
      3 print("Test")
      4 print(a)

NameError: name 'sys' is not defined

I would like this saved in a file and not shown in the notebook. 我希望将其保存在文件中,而不在笔记本中显示。 What is the correct code for this? 正确的代码是什么?

I think that the problem here is that IPython kernels spawned for the notebook use a ZMQInteractiveShell instance, which catches the errors before they make it to stderr, in order to send the error information to the various potential frontends (consoles, jupyter notebooks, etc). 认为这里的问题是为笔记本计算机生成的IPython内核使用ZMQInteractiveShell实例,该实例在将错误传递给stderr之前捕获了错误,以便将错误信息发送到各种潜在的前端(控制台,jupyter笔记本计算机等)。 。 See ipykernel/ipkernel.py#L397-L413 for the code which catches exceptions, then InteactiveShell._showtraceback for the base implementation (print to sys.stderr ), and ZMQInteractiveShell._showtraceback for that used by notebook kernels (send stderr-channel messages over zmq to frontends). ipykernel / ipkernel.py#L397-L413针对捕获异常,则代码InteactiveShell._showtraceback为基实现(印刷到sys.stderr )和ZMQInteractiveShell._showtraceback对于由笔记本内核使用(通过发送标准错误信道消息zmq到前端)。

If you're not bothered about getting exact stderr output, you could take advantage of IPython's existing error logging , which logs errors to a StreamHandler with the prefix "Exception in execute request:" . 如果您不担心获得准确的stderr输出,则可以利用IPython 现有的错误日志记录 ,该日志记录将错误记录到带有前缀"Exception in execute request:"StreamHandler "Exception in execute request:" To use this, set the ipython log level, and alter the provided handler's stream: 要使用此功能,请设置ipython日志级别,并更改提供的处理程序的流:

import logging
import sys

my_stderr = sys.stderr = open('errors.txt', 'w')  # redirect stderr to file
get_ipython().log.handlers[0].stream = my_stderr  # log errors to new stderr
get_ipython().log.setLevel(logging.INFO)  # errors are logged at info level

Alternatively, to get your shell errors to print directly to a file without alteration, you can monkey-patch the _showtraceback method to print traceback to file as well as zmq message queues: 另外, _showtraceback您的Shell错误不经更改直接直接打印到文件,可以对_showtraceback方法进行猴子补丁,以将回溯打印到文件以及zmq消息队列:

import sys
import types

# ensure we don't do this patch twice
if not hasattr(get_ipython(), '_showtraceback_orig'):
    my_stderr = sys.stderr = open('errors.txt', 'w')  # redirect stderr to file
    # monkeypatch!
    get_ipython()._showtraceback_orig = get_ipython()._showtraceback

    def _showtraceback(self, etype, evalue, stb):
        my_stderr.write(self.InteractiveTB.stb2text(stb) + '\n')
        my_stderr.flush()  # make sure we write *now*
        self._showtraceback_orig(etype, evalue, stb)

    get_ipython()._showtraceback = types.MethodType(_showtraceback, get_ipython())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有人知道如何保存 jupyter notebook 中单元格的图像输出吗? - anybody know how to save image output from cells in jupyter notebook? 如何将 xgboost 的特征重要性图从 Jupyter 笔记本保存到文件 - How to save feature importance plot of xgboost to a file from Jupyter notebook 从 Jupyter Notebook 运行并保存到 .py 文件 - Run from and save to .py file from Jupyter Notebook 如何保存带有输出的jupyter笔记本 - How to save a jupyter notebook with outputs 如何将 selenium(jupyter notebook)中的页面源保存到本地驱动器上的 txt 文件中? - how to save page source from selenium (jupyter notebook) to a txt file on local drive? 如何使用 python 命令将 Jupyter 笔记本输出保存在文件中? - How to save Jupyter notebook output in a file using python command? 如何使用自定义的动态文件名以编程方式保存 jupyter notebook 的 pdf - How to programatically save pdf of jupyter notebook with a custom, dynamic, file name 如何在 jupyter notebook 上将 python 脚本保存为 .py 文件 - How to save python script as .py file on jupyter notebook 如何在 GitHub 上保存代码文件并在 Jupyter Notebook 上运行? - How to save code file on GitHub and run on Jupyter notebook? 防止 Jupyter Notebook 合并 markdown 个单元格 - Prevent Jupyter Notebook from merging markdown cells
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM