Вопрос

I'm trying to execute python script which use pyparsing in C# with a help of IronPython. But when I try to run the script I get the ImportException that there is No module named pyparsing. I tried to add a path to a dir consisting pyparsing, but I still didn't managed how to run it proper way.

Here's the C# code:

string ExecutePythonScript(string path, string text)
    {
        ScriptEngine engine = Python.CreateEngine();
        ScriptScope scope = engine.CreateScope();

        string dir = System.IO.Path.GetDirectoryName("pyparsing-1.5.7");

        ICollection<string> paths = engine.GetSearchPaths();

        if (!String.IsNullOrEmpty(dir))
        {
            paths.Add(dir);
        }
        else
        {
            paths.Add(Environment.CurrentDirectory);
        }
        engine.SetSearchPaths(paths);

        scope.SetVariable("text", text);
        engine.ExecuteFile(path, scope);

        return scope.GetVariable("result");
    }

Of course in the beggining of the python script I import pyparsing.

Это было полезно?

Решение

Thanks to my friend I found what was wrong.

  1. Unpacked pyparsing package had to be placed in the Debug folder of C# app in a folder named Lib. (I suppose it also could be in folder with another name, but this was faster for me.)
  2. Thanks to this page I also realized that I need to add some lines of code into the C# app.

So now it's:

    string ExecutePythonScript(string path, string text)
    {
        ScriptEngine engine = Python.CreateEngine();
        ScriptScope scope = engine.CreateScope();

        ICollection<string> Paths = engine.GetSearchPaths();
        Paths.Add(".");
        Paths.Add("D:\\DevTools\\IronPython 2.7\\Lib");
        Paths.Add("D:\\DevTools\\IronPython 2.7\\DLLs");
        Paths.Add("D:\\DevTools\\IronPython 2.7");
        Paths.Add("D:\\DevTools\\IronPython 2.7\\lib\\site-packages");
        engine.SetSearchPaths(Paths);

        scope.SetVariable("text", text);
        engine.ExecuteFile(path, scope);
        (...)

And it's at least not creating that Exception.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top