<p>我正在从C#调用并执行python(.py)文件,但在此之前,我想验证该文件是否为有效的python文件或任何语法/代码错误</p>
<p>如何在执行文件之前动态编译python代码文件</p>
<p>下面是我的代码</p>
<pre><code> using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using IronPython.Hosting;//for DLHE
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
try
{
var scriptSource = engine.CreateScriptSourceFromFile(@"C:\Nidec\PythonScript\download_nrlist.py", Encoding.UTF8, Microsoft.Scripting.SourceCodeKind.File);
var compiledCode = scriptSource.Compile();
compiledCode.Execute(scope);
//engine.ExecuteFile(@"C:\Nidec\PythonScript\download_nrlist.py", scope);
// get function and dynamically invoke
var calcAdd = scope.GetVariable("CalcAdd");
result = calcAdd(34, 8); // returns 42 (Int32)
}
catch (Exception ex)
{
ExceptionOperations ops = engine.GetService<ExceptionOperations>();
Console.WriteLine(ops.FormatException(ex));
}
return result;
</code></pre>