如何在IronPython 3.4中获取Python风格的Traceback错误信息?
解决IronPython获取标准Python格式错误信息的问题
要在IronPython中获取和标准Python一致的错误输出格式,你需要利用IronPython内置的异常格式化工具,而非直接捕获CLR异常并输出。以下是修改后的实现方案:
首先添加必要的命名空间引用:
using IronPython.Hosting; using IronPython.Runtime.Exceptions; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using UnityEngine; using System.IO;
然后调整Start方法的逻辑:
void Start() { var engine = Python.CreateEngine(); var scope = engine.CreateScope(); // 获取IronPython的异常格式化服务 var exceptionOps = engine.GetService<ExceptionOperations>(); string code = @"print(var)"; try { // 指定脚本类型为交互式代码,让错误信息文件名显示为<stdin> var source = engine.CreateScriptSourceFromString(code, SourceCodeKind.InteractiveCode); source.Execute(scope); } catch (SystemException e) { // 格式化异常,生成标准Python风格的Traceback string formattedError = exceptionOps.FormatException(e); Debug.Log(formattedError); } }
关键说明
ExceptionOperations是IronPython专门用于处理异常格式化的服务,能将CLR层面的异常转换为标准Python Traceback格式的字符串。- 指定
SourceCodeKind.InteractiveCode可以让错误信息中的文件标识和标准Python交互模式保持一致(显示为<stdin>)。 - 捕获
SystemException是因为IronPython抛出的Python相关异常均继承自该类,能精准覆盖场景内的错误类型。
修改后即可得到你期望的输出:
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'var' is not defined
内容的提问来源于stack exchange,提问作者Riley B
相关产品推荐
相关产品推荐

