Is it possible to check the syntax of a python script before running it when making use of IronPython and C#?

StackOverflow https://stackoverflow.com/questions/23289278

  •  09-07-2023
  •  | 
  •  

Question

Since I solved the issue of checking the syntax, I shall elaborate on how I did this. I will use my own implementation as an example.

First of all what have I used and how I have used it?

I made use of the ast module available in IronPython since version 2.6 (I made use of 2.7.4(1)). The ast module builds an abstract syntax tree(2) (ast for short) of code supplemented to the module. This function made it possible for me to know if a script had a good syntax or not. As such I knew if the module could successfully create a tree it meant the syntax was OK, if an exception occurred it meant NOT OK.

How have I implemented it?

Implementation was not the easiest, but my thanks goes out to Pawel Jasinski certain errors I had were quickly resolved thanks to him.

There are two parts of code I shall discuss. First of all I shall discuss the Python part which I call from my C# code.

Python:

import System
import sys
sys.path.append(r"C:\Program Files (x86)\IronPython 2.7\Lib") #This reference was vital, without it I wouldn't be able to check any code because Ironpython would just mention "no module named 'ast' "
import ast                                                    #The ast module is loaded to check the script for any errors.

def syntaxcheck(fileurl):                                     #The method that runs the parse, I call this method in my C# code and provide the URL directly from an openfiledialog event.
    result = ast.parse(open(fileurl, 'r').read())             
    return result

It is important to note several things:

  • C:\Program Files (x86)\IronPython 2.7\Lib may be different because of what version of Windows you're running and how you installed IronPython. This url is the default installation location on Windows 7 64bit.
  • import ast MUST be behind the import sys and the path.append line.
  • Be sure that the syntax of this file is correct, but this is more likely to not occur because the code will not run anyway. I made use of Python Tools for Visual Studio 2.0 (3) this make creating Python file a lot easier and it doesn't require you to install other software than Visual Studio to create Python files.

Now the C# code (this is from opening an openFileDialog since I used it that way, however this doesn't mean that you can't use it in another function or method):

private void ofdPython_FileOk(object sender, CancelEventArgs e)
{
    //I made use of a simple MessageBox to give the user an easy way to see what file was faulty. There are better methods to do this but I will not elaborate on this here.
    String strErrorSummarization = "Due to (an) error(s) in the selected files, it is not possible to run the selected test cases.\nHere is the list that shows all files until the erroneous file:\n";

    //We add all files we want to use to a list which we will later turn into an array.
    listScripts.AddRange((string[])ofdPython.FileNames);

    //Create the runtime that will run the script through the IronPython interpreter.
    var ipy = Python.CreateRuntime();

    //Convert list to array
    string[] saScripts = listScripts.ToArray();

    //Loop trough all selected files and check them for their syntax.
    for (int i = 0; i < listScripts.ToArray().Length; i++)
    {
        try
        {
            //Set pythonscript to use as checker the location can be anything you want as long as the file is available when running this code
            dynamic syntaxCheck = ipy.UseFile("c:\\psyntax.py");

            syntaxCheck.syntaxcheck(saScripts[i]);

            //Add a note to the string we made to tell the checked script is OK
            strErrorSummarization += saScripts[i].ToString() + " ---> contains no errors.\n";

        }
        catch (Exception e)
        {
            strErrorSummarization += saScripts[i].ToString() + " ---> IS ERRONEOUS.\n\nAll loaded files have been dropped, please check the above file for syntax errors!";
            //Empty the selected files list
            listScripts.Clear();
            //Show the list of checked files including the file which had an error. If there are any extra file with error behind the first one, they will not be seen since the checking stop after the first faulty file
            MessageBox.Show(strErrorSummarization, "Error(s) found in the selected scripts", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }            
}

It is important that following references is made in the C# code:

  • using IronPython.Hosting;

And following references must be made too:

Name                                    Path

Microsoft.Scripting.dll                 C:\Program Files(x86)\IronPython 2.7\Microsoft.Scripting.dll               
IronPython.Modules.dll                  C:\Program Files(x86)\IronPython 2.7\IronPython.Modules.dll
IronPython.dll                          C:\Program Files(x86)\IronPython 2.7\IronPython.dll

The above code has comments explaining what I do and why. If there are any questions, feel free to ask them :-)

Because my reputation is to low and I am unable to add extra hyperlinks then one here is the list of links that are recognized by the () brackets with a number in them:

  (1): http://ironpython.codeplex.com/downloads/get/723206   ---> IronPython 2.7.4
  (2): http://en.wikipedia.org/wiki/Abstract_syntax_tree     ---> Info on AST
  (3): https://pytools.codeplex.com/releases/view/103102     ---> Python Tools for Visual Studio 2.0
Was it helpful?

Solution

The solution I made is shown where I originally asked my question. Since I solved my own issue and posted the solution here I can say this is the answer to the question. Thanks again to Pawel Jasinski! :-) Baikuriu also thanks for giving the hint to check for the AST module.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top