Mac下Jupyter Notebook中Pythonnet调用C#异常无输出且内核挂起
Pythonnet调用C#函数时Jupyter内核挂起问题
问题现象
- 使用pythonnet在Python中调用C#函数时,Jupyter Notebook中一旦触发错误,内核会无限挂起且无任何错误信息输出
- 终端运行相同Python脚本时,能正常捕获错误信息并终止进程
- Windows环境下的团队成员在Jupyter Notebook中无此问题,推测与macOS操作系统相关
- 传入合法参数时Jupyter Notebook可正常输出结果,仅在出错时出现内核挂起
环境信息
- 操作系统:macOS Ventura 13.6(M1芯片)
- VS 2022
- Python 3.9.12
- IPython 8.0.0
- jupyter_client 7.4.9
- jupyter_core 5.3.0
- jupyter_server 2.5.0
示例代码
C#项目代码(HelloWorld)
// Project HelloWorld namespace MyLibrary { public class Adder { public int Add(int left, int right) { return left + right; } public static void Main(string[] args) { } } }
Python调用代码
from clr_loader import get_coreclr from pathlib import Path from pythonnet import set_runtime from os.path import abspath # 设置已发布的C#项目路径 libfolder = Path(abspath("")) / "lib" set_runtime(get_coreclr(runtime_config=libfolder / "clr_runtime.json")) import clr clr.AddReference(str((libfolder / "HelloWorld").absolute())) from MyLibrary import Adder adder = Adder() print(f"My C# Adder method: {adder.Add(3.2, 4)}") # 传入float而非int触发错误
错误表现对比
终端运行结果(正常输出错误)
Python.Runtime.PythonException: an integer is required The above exception was the direct cause of the following exception: System.ArgumentException: an integer is required in method Int32 Add(Int32, Int32) ---> Python.Runtime.PythonException: an integer is required --- End of inner exception stack trace --- The above exception was the direct cause of the following exception: System.AggregateException: One or more errors occurred. (an integer is required in method Int32 Add(Int32, Int32)) ---> System.ArgumentException: an integer is required in method Int32 Add(Int32, Int32) ---> Python.Runtime.PythonException: an integer is required --- End of inner exception stack trace --- --- End of inner exception stack trace --- The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/virgfrey/Projects/Hello World/test.py", line 17, in <module> print(f"My C# Adder method: {adder.Add(3.2,4)}") TypeError: No method matches given arguments for Adder.Add: (<class 'float'>, <class 'int'>)
Jupyter Notebook运行结果
内核无限挂起,无任何错误信息输出
临时解决方案
- 提前参数校验:在调用C#函数前,对传入参数的类型、取值范围做校验,从源头避免触发错误
- 捕获异常并强制终止:在Python代码中添加try-except块,捕获异常后主动终止内核进程(仅适用于测试阶段),示例:
try: print(f"My C# Adder method: {adder.Add(3.2, 4)}") except Exception as e: print(f"Error occurred: {e}") # 强制终止内核 import os os._exit(1)
- 升级依赖版本:尝试将IPython、jupyter相关包以及pythonnet更新至最新稳定版,排查是否为旧版本兼容性问题导致的异常处理失效
内容的提问来源于stack exchange,提问作者Virginia
相关产品推荐
相关产品推荐

