繁体   English   中英

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

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

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

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

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

我如何实施呢?

实施并不是最容易的,但是我要感谢Pawel Jasinski某些错误,由于他,我很快就解决了。

我将讨论代码的两个部分。 首先,我将讨论从C#代码调用的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 64bit上的默认安装位置。
  • import ast必须在import syspath.append行之后。
  • 确保此文件的语法正确,但是由于代码始终无法运行,因此很有可能不会发生这种情况。 我使用了适用于Visual Studio 2.0的Python工具(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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM