首页 > 解决方案 > IronPython:通过 C# 代码进行脚本验证

问题描述

我在 C#/.Net Core 3.1 项目中使用 IronPython,我需要能够在生产环境中执行之前验证脚本。

我找到了这个解决方案,创建了我的自定义Microsoft.Scripting.Hosting.ErrorListener实现:

public class IronPythonListener : ErrorListener
{
    public List<ValidationError> Errors = new List<ValidationError>();

    public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
    {
        Errors.Add(new ValidationError
        {
            Message = message,
            ErrorCode = errorCode,
            Severity = severity,
            Span = span
        });
    }
}

然后将它的一个实例传递给该Microsoft.Scripting.Hosting.ScriptSource.Compile(ErrorListener)方法:

IronPythonListener listener = new IronPythonListener();
ScriptEngine engine = Python.CreateEngine();
ScriptSource scriptSource = engine.CreateScriptSourceFromString(script, SourceCodeKind.AutoDetect);
CompiledCode code =  scriptSource.Compile(listener);

listener.Errors列表中,我找到了所有编译错误。

此解决方案有效,但出于我的目的,它并不完整,例如:

对我来说似乎很奇怪的另一件事是,我能找到的所有错误都是类型Severity.FatalError(例如通过my_var = 6 +),但我找不到任何Severity.Erroror Severity.Warning

有没有办法在不执行我编译的脚本的情况下改进验证?

提前感谢您的帮助,不幸的是我找不到这么多关于此的文档。

编辑:我发现了一些在线验证器(例如https://repl.it/languages/python3http://pep8online.com/),它们也没有提供完整的 python 验证(在前一个中,验证被处理IDE 更好,但5 + "some text"仅在执行时检测到错误)。当然,我可以尝试执行脚本并在listener.Errors为空时捕获异常,但最好避免这种情况。

编辑 2:我也尝试了这个解决方案,使用单独的 python 脚本来验证我的,但是对于未定义的函数和错误的运算符使用,我也有同样的问题。

标签: pythonc#ironpython

解决方案


推荐阅读