在使用IronPython和C#时,是否可以在运行之前检查python脚本的语法?

时间:2014-04-25 09:32:04

标签: c# python ironpython

由于我解决了检查语法的问题,我将详细说明我是如何做到这一点的。我将以自己的实现为例。

首先,我使用了什么以及如何使用它?

我使用了自2.6版本以来IronPython中可用的ast模块(我使用了2.7.4(1))。 ast模块构建了补充到模块的代码的抽象语法树(2)(简称ast)。这个函数使我可以知道脚本是否具有良好的语法。因此,我知道模块是否可以成功创建树,这意味着语法正常,如果发生异常则意味着不行。

我是如何实施的?

实施并不是最简单的,但我要感谢Pawel Jasinski由于他的原因,我很快就解决了一些错误。

我将讨论两部分代码。首先,我将讨论我从C#代码调用的Python部分。

的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

重要的是要注意几件事:

  • C:\Program Files (x86)\IronPython 2.7\Lib可能会有所不同,因为 您正在运行的Windows版本以及安装方式 IronPython的。此URL是Windows 7 64位上的默认安装位置。
  • import ast必须位于import syspath.append行后面。
  • 请确保此文件的语法正确,但更可能不会发生这种情况,因为代码无论如何都不会运行。我使用Python Tools for Visual Studio 2.0(3)这使得创建Python文件变得更加容易,并且它不需要安装除Visual Studio之外的其他软件来创建Python文件。

现在是C#代码(这是因为我以这种方式使用它来打开openFileDialog,但这并不意味着你不能在另一个函数或方法中使用它):

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);
        }
    }            
}

在C#代码中进行以下引用非常重要:

  • using IronPython.Hosting;

还必须提供以下参考:

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

以上代码的评论解释了我的工作和原因。如果有任何问题,请随时问他们: - )

因为我的声誉很低而且我无法添加额外的超链接,所以这里的一个链接列表被()括号识别,其中包含数字:

  (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

1 个答案:

答案 0 :(得分:0)

我所提出的解决方案显示了我最初提出问题的地方。由于我解决了自己的问题并在此处发布了解决方案,我可以说这是问题的答案。再次感谢Pawel Jasinski! :-) Baikuriu也感谢您提供检查AST模块的提示。