Skip to content

Instantly share code, notes, and snippets.

@hzhu212
Last active December 7, 2023 01:59
Show Gist options
  • Save hzhu212/9dbeb6640ca2e5cd34ca7d80ae37e98a to your computer and use it in GitHub Desktop.
Save hzhu212/9dbeb6640ca2e5cd34ca7d80ae37e98a to your computer and use it in GitHub Desktop.
一些 Jupyter 技巧

任意一个 cell 出现异常执行 callback

# this function will be called on exceptions in any cell
def when_exception(shell, etype, evalue, tb, tb_offset=None):
    # still show the error within the notebook, don't just swallow it
    shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)

    err_msg = f'Unexpected exception occured: {repr(evalue)}'
    logger.error(err_msg)
    print('do your stuff here ...')
    

# this registers a custom exception handler for the whole current notebook
from IPython import get_ipython
get_ipython().set_custom_exc((Exception,), when_exception)

在 jupyter 中绘制动态更新的图像

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, clear_output


fig = plt.figure()
ax = fig.add_subplot(1, 1, 1) 

for i in range(20):
    x = np.arange(0, i, 0.1);
    y = np.sin(x)
    
    ax.set_xlim(0, i)
    
    ax.cla()
    ax.plot(x, y)
    display(fig)
    
    clear_output(wait = True)
    plt.pause(0.5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment