使用IronPython和C#时是否可以在运行之前检查python脚本的语法? [英] Is it possible to check the syntax of a python script before running it when making use of IronPython and C#?

查看:73
本文介绍了使用IronPython和C#时是否可以在运行之前检查python脚本的语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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.

我如何实现它?

实施不是最简单的方法,但是我要感谢 Pawel Jasinski 我遇到的某些错误很快得到解决感谢他.

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

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

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可能有所不同,因为 您正在运行的Windows版本以及如何安装 IronPython.该URL是Windows 7 64bit上的默认安装位置.
  • import ast必须位于import syspath.append行之后.
  • 请确保该文件的语法正确,但是由于代码始终无法运行,因此很有可能不会发生这种情况.我使用了适用于Visual Studio 2.0的Python工具(3),这使创建Python文件变得更加容易,并且不需要安装Visual Studio以外的其他软件即可创建Python文件.
  • 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.

现在使用C#代码(这是因为我以这种方式使用,因此打开了openFileDialog,但这并不意味着您不能在其他函数或方法中使用它)

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

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

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

推荐答案

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

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.

这篇关于使用IronPython和C#时是否可以在运行之前检查python脚本的语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆