<p>您可以使用以下代码检查IronPython代码是否存在错误:</p>
<pre><code>public static void CheckErrors()
{
var engine = Python.CreateEngine();
var fileName = "myscript.py";
var source = engine.CreateScriptSourceFromString(File.ReadAllText(fileName), fileName, SourceCodeKind.File);
var sourceUnit = HostingHelpers.GetSourceUnit(source);
var result = new Result();
var context = new CompilerContext(sourceUnit, new PythonCompilerOptions(), result);
var parser = Parser.CreateParser(context, new PythonOptions());
parser.ParseFile(false);
// Use the collected diagnostics from the result object here.
}
public class Result : ErrorSink
{
public override void Add(SourceUnit source, string message, SourceSpan span, int errorCode, Severity severity)
{
Add(message, source.Path, null, null, span, errorCode, severity);
}
public override void Add(string message, string path, string code, string line, SourceSpan span, int errorCode, Severity severity)
{
if (severity == Severity.Ignore)
return;
// Collect diagnostics here.
}
}
</code></pre>
<p>我们使用此代码检查AlterNET Studio产品的IronPython脚本中的错误。下面是它的外观:</p>
<p><a href="https://i.stack.imgur.com/OOGMT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OOGMT.png" alt="AlterNET Studio IronPython script errors"/></a></p>