如何让pdoc处理Jupyter Notebook代码单元时跳过错误继续执行
问题描述
现有一套通过Panel选择Jupyter Notebook的代码,功能是将Notebook中的每个代码单元保存为独立.py文件,通过pdoc生成文档后再把文档添加回Notebook末尾。但部分仅包含test()调用或@property注解的代码单元会触发pdoc导入错误,导致循环直接中断,剩余单元无法继续生成文档。此前尝试用try-except捕获异常但未生效,求能在出错时跳过当前单元、继续执行剩余单元的实现方案。
现有代码
for file in files.value: source = file dest = add_suffix(source, " documented") dest1 = "/home/dqm/pydev/notebook_copy" shutil.copy(source,dest) document_note = shutil.copy(dest,dest1) os.remove(dest) notebook = get_notebook(document_note) for filename, code in get_code_cells_content(notebook['cells']): save_as_python_file(filename, code) print('documentation starting') #!pdoc --html ./'{filename}'.py -o ./notebook_copy/document res = Popen(["pdoc", "--html", f"./{filename}.py", "-o", "./notebook_copy/document"], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate() # template status.value += res[0].decode("utf-8") + "\n" status.value += res[1] .decode("utf-8") + "\n" #!pdoc --output-dir=./notebook_copy/document ./'{filename}'.py res = Popen(["pdoc", "--output-dir=./notebook_copy/document", f"./{filename}.py"], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate() # template status.value += res[0].decode("utf-8") + "\n" status.value += res[1] .decode("utf-8") + "\n" create_new_cell(document_note,filename) os.remove(f'{filename}.py') remove("./notebook_copy/document") display(pn.widgets.StaticText(name='documented', value='succesfully')) pass # call here the documentation creator
解决方案
核心是把单个代码单元的完整处理逻辑包裹在try-except块中,确保任何环节出错时都能捕获异常、清理资源,然后跳过当前单元继续执行。之前try-except未生效大概率是因为只包裹了pdoc调用部分,而错误可能出现在文件保存、pdoc执行、单元格创建等任意步骤,或者未捕获到具体异常类型。
修改后的代码如下:
for file in files.value: source = file dest = add_suffix(source, " documented") dest1 = "/home/dqm/pydev/notebook_copy" shutil.copy(source,dest) document_note = shutil.copy(dest,dest1) os.remove(dest) notebook = get_notebook(document_note) for filename, code in get_code_cells_content(notebook['cells']): # 将单个单元的处理逻辑全部放入try块 try: save_as_python_file(filename, code) print('documentation starting') # 执行pdoc命令(保留原有的两次调用逻辑) res = Popen(["pdoc", "--html", f"./{filename}.py", "-o", "./notebook_copy/document"], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate() status.value += res[0].decode("utf-8") + "\n" status.value += res[1].decode("utf-8") + "\n" res = Popen(["pdoc", "--output-dir=./notebook_copy/document", f"./{filename}.py"], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate() status.value += res[0].decode("utf-8") + "\n" status.value += res[1].decode("utf-8") + "\n" create_new_cell(document_note,filename) display(pn.widgets.StaticText(name='documented', value='successfully')) except Exception as e: # 捕获所有异常,打印错误信息到status error_msg = f"处理单元 {filename} 出错: {str(e)}\n" print(error_msg) status.value += error_msg finally: # 无论成功或失败,都强制清理临时文件和目录 if os.path.exists(f'{filename}.py'): os.remove(f'{filename}.py') doc_dir = "./notebook_copy/document" if os.path.exists(doc_dir): remove(doc_dir) pass # call here the documentation creator
关键改动说明:
- 把单个代码单元的所有操作(保存文件、pdoc调用、创建单元格、显示提示)都放进
try块,确保任何步骤出错都能被捕获。 - 使用
finally块强制清理临时文件和目录,避免残留垃圾文件。 - 捕获
Exception(最宽泛的异常类型)确保不会漏掉任何错误,如果知道具体异常类型(比如ImportError),可以替换成更精准的类型以减少误捕获。 - 出错时打印详细错误信息到
status,方便排查问题,同时不中断整个循环。
内容的提问来源于stack exchange,提问作者Samira
相关产品推荐
相关产品推荐

