python - 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
列表中,我找到了所有编译错误。
此解决方案有效,但出于我的目的,它并不完整,例如:
- 如果传递的脚本类似于
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
or Severity.Warning
。
有没有办法在不执行我编译的脚本的情况下改进验证?
提前感谢您的帮助,不幸的是我找不到这么多关于此的文档。
编辑:我发现了一些在线验证器(例如https://repl.it/languages/python3或http://pep8online.com/),它们也没有提供完整的 python 验证(在前一个中,验证被处理IDE 更好,但5 + "some text"
仅在执行时检测到错误)。当然,我可以尝试执行脚本并在listener.Errors
为空时捕获异常,但最好避免这种情况。
编辑 2:我也尝试了这个解决方案,使用单独的 python 脚本来验证我的,但是对于未定义的函数和错误的运算符使用,我也有同样的问题。
解决方案
推荐阅读
- java - 如何在 RestEasy 服务中使用 OpenSAML 处理 SAML v2 响应
- excel - Excel - INDEX MATCH NA 错误 - 排序顺序
- excel - 使用 python 过滤列并填充新 Excel 文件中的相应行
- amazon-web-services - 如何使用 AWS Cli 启动具有自定义根卷 ebs 大小(超过 8GB)的 ec2 实例
- laravel-5 - Laravel /broadcasting/auth 返回(找到 302)并重定向到登录页面
- webpack - 不能使用 webpack-dev-server 作为 https 网站的代理 - ERR_TLS_CERT_ALTNAME_INVALID
- c# - 由 ref 传递且不带 ref 的引用类型
- php - 从多维数组中获取时间线
- java - 写入 HID 键盘适用于 Linux,但不适用于 Windows
- c# - 如何正确实现系统托盘注销操作