如何在c#中使用IronPython动态编译python py文件

2024-05-15 03:51:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从C#调用并执行python(.py)文件,但在此之前,我想验证该文件是否为有效的python文件或任何语法/代码错误

如何在执行文件之前动态编译python代码文件

下面是我的代码

      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;

Tags: 文件代码pyhttpvarextensionsazureengine
2条回答

我决定在执行之前编译代码。这是我找到的唯一方法。更新了代码

您可以使用以下代码检查IronPython代码是否存在错误:

public static void CheckErrors()
{
    var engine = Python.CreateEngine();

    var fileName = "myscript.py";
    var source = engine.CreateScriptSourceFromString(File.ReadAllText(fileName), fileName, SourceCodeKind.File);

    var sourceUnit = HostingHelpers.GetSourceUnit(source);

    var result = new Result();
    var context = new CompilerContext(sourceUnit, new PythonCompilerOptions(), result);
    var parser = Parser.CreateParser(context, new PythonOptions());
    parser.ParseFile(false);

    // Use the collected diagnostics from the result object here.
}

public class Result : ErrorSink
{
    public override void Add(SourceUnit source, string message, SourceSpan span, int errorCode, Severity severity)
    {
        Add(message, source.Path, null, null, span, errorCode, severity);
    }

    public override void Add(string message, string path, string code, string line, SourceSpan span, int errorCode, Severity severity)
    {
        if (severity == Severity.Ignore)
            return;

        // Collect diagnostics here.
    }
}

我们使用此代码检查AlterNET Studio产品的IronPython脚本中的错误。下面是它的外观:

AlterNET Studio IronPython script errors

相关问题 更多 >

    热门问题