问题描述
我正在C#/。Net Core 3.1项目中使用IronPython,在生产环境中执行脚本之前,我需要能够验证脚本。
我找到了this solution,创建了自定义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
列表中,我找到了所有编译错误。
此解决方案有效,但出于我的目的,它并不完整,因为例如:
- 如果所传递的脚本类似于
my_var = 5 + "some text"
,则listener.Errors
为空,即使该脚本无法执行,该脚本也被认为是有效的(实际上,它引发了unsupported operand type(s) for +: 'int' and 'str'
异常) - 如果所传递的脚本包含对未定义函数的调用(例如,
length(my_string)
而不是len(my_string)
),则该脚本被视为有效
令我感到奇怪的另一件事是,我可以找到的所有错误都是Severity.FatalError
类型(例如,传递my_var = 6 +
),但是我找不到任何Severity.Error
或Severity.Warning
。
有没有一种方法可以改进验证,而无需执行我的编译脚本?
在此先感谢您的帮助,不幸的是我找不到太多的文档。
编辑:我找到了一些在线验证器(例如https://repl.it/languages/python3或http://pep8online.com/),但它们也没有提供完整的python验证(在前一个验证中, IDE可以更好地处理它,但仅在执行时检测到5 + "some text"
错误)。当然,我可以尝试执行脚本并在listener.Errors
为空时捕获异常,但是最好避免这种情况。
编辑2 :我也尝试了this solution,使用单独的python脚本来验证我的操作,但是在未定义的函数和错误的运算符用法上也存在相同的问题。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)