0

I am calling and executing python(.py) files from C# but before that I would like to validate file either it is valid python file or any syntax/code errors.

How can I compile python code file dynamically before executing file?

Below is my 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;
2
  • I assume you mean in IronPython? Commented May 19, 2021 at 6:52
  • The way you detect syntax errors is by running the code and catching any exceptions. There's no way to detect coding errors. Commented May 19, 2021 at 6:56

2 Answers 2

0

I decided to compile the code before executing. that is the one way I found. Updated the code.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the following code to check the IronPython code for errors:

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.
    }
}

We used this code to check errors in IronPython scripts for our AlterNET Studio product. Here is how it looks:

AlterNET Studio IronPython script errors

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.