最近,我已经开始使用pythonNet从Csharp执行脚本,到目前为止,我在csharp中一直在执行一个算法,它运行得很好:
using (Py.GIL())
{
PythonEngine.Initialize();
using (var scope = Py.CreateScope())
{
string code = File.ReadAllText(fileName);
var scriptCompiled = PythonEngine.Compile(code, "Analyze.py");
scope.Execute(scriptCompiled);
dynamic func = scope.Get("predictFromData");
PyList Pydata = new PyList(data.ToPython());
PyTuple rettp = new PyTuple(func(Pydata));
PyList pyIndexList = new PyList(rettp[0]);
foreach (PyObject intobj in pyIndexList)
{
indexList.Add(intobj.As<int>());
}
}
}
但是我想知道是否有一种方法可以在实际运行代码之前检查代码是否可以执行,因为它与编译的代码一起工作,而且PythonNet确实需要外部的python安装来查看是否每个模块都在这里,等等……如果在python中不可能的话,然后切换回我以前的csharp算法。
现在,我只想简单地执行python单元测试,用虚拟值导入模块和测试函数,并将异常和单元测试值返回到csharp代码中,但是如果有人有想法的话,我更喜欢一种更干净的方法。干杯。
发布于 2022-02-19 11:22:15
有几件事你可以在这里检查:
首先是查看Python代码是否具有正确的语法,可以使用如下代码来完成:
public static IReadOnlyList<ScriptCompilationDiagnostic> CheckErrors(ScriptEngine engine, string script, string fileName, RunFlagType mode)
{
try
{
PythonEngine.Compile(script, fileName, mode);
}
catch (PythonException e)
{
dynamic error = e.Value;
return new[]
{
new ScriptCompilationDiagnostic
{
Kind = ScriptCompilationDiagnosticKind.Error,
Line = error.lineno - 1,
Column = error.offset - 1,
Message = error.msg,
Code = error.text,
FileName = error.filename,
},
};
}
return new ScriptCompilationDiagnostic[0];
}
其次,您可以使用如下代码检查Python是否安装在目标计算机上:
var pythonHome = TryGetFullPathFromPathEnvironmentVariable("python.exe");
private static string? TryGetFullPathFromPathEnvironmentVariable(string fileName)
{
if (fileName.Length >= MAXPATH)
throw new ArgumentException($"The executable name '{fileName}' must have less than {MAXPATH} characters.", nameof(fileName));
var sb = new StringBuilder(fileName, MAXPATH);
return PathFindOnPath(sb, null) ? sb.ToString() : null;
}
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode, SetLastError = false)]
private static extern bool PathFindOnPath([In, Out] StringBuilder pszFile, [In] string[]? ppszOtherDirs);
如果您的脚本使用的是第三方模块,您可以检查它们是否也已安装:
public bool IsModuleInstalled(string module)
{
string moduleDir = Path.Combine(PythonHome, "Lib", "site-packages", module);
return Directory.Exists(moduleDir) && File.Exists(Path.Combine(moduleDir, "__init__.py"));
}
请注意,Python.NET并不正式支持最新的PythonVersion3.9,因此您也可以从这里分发和安装嵌入式Python:
https://www.python.org/ftp/python/3.7.3/
与所有所需的第三方模块一起作为轮子。
我们在我们的AlterNET工作室产品中使用这种方法来检查我们的Python调试器是否安装了基于debugger的Python,并为我们的基于Python.NET的划线机/调试器安装了带有轮子的嵌入式Python。
https://stackoverflow.com/questions/71172143
复制相似问题