csi
csi

Reputation: 240

setup ironpython: Module not found

I'm using Ironpython for the first time to Import a Python Script to C#. I get the error "No module named numpy", but I don't know why. I read that I have to add my path of my modules to my python script. This is my python script:

import numpy as np
import sys
sys.path.append(r"C:\Users\abc\CSharp\PythonScriptExecution1\packages\IronPython.2.7.9\lib")
sys.path.append(r"C:\Users\abc\PycharmProjects\untitled3\venv\Lib")
sum = np.sum([0.5, 1.5])
print(sum)

The second path is the path which is also used as project interpreter in Pycharm for the python.exe.

My C# code is this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PythonScriptExecution2
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine =
                IronPython.Hosting.Python.CreateEngine();
            // We execute this script from Visual Studio 
            // so the program will be executed from bin\Debug or bin\Release
            Microsoft.Scripting.Hosting.ScriptSource pythonScript =
                pythonEngine.CreateScriptSourceFromFile("C:/Users/abc/PycharmProjects/untitled3/test.py");
            pythonScript.Execute();
        }
    }
}

Running the Python script in Pycharm works fine, but importing it to C# results in the error mentioned above. Can someone help me how to set the right paths?

edit: If it doesn't work, does anyone know any other way to run a python script with C#?

Upvotes: 3

Views: 4118

Answers (1)

Default Writer
Default Writer

Reputation: 2566

Related to How to add modules to Iron Python?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PythonScriptExecution2
{
    class Program
    {
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine eEngine =
                IronPython.Hosting.Python.CreateEngine();
            // We execute this script from Visual Studio 
            // so the program will be executed from bin\Debug or bin\Release
            Microsoft.Scripting.Hosting.ScriptSource pythonScript =

            ICollection<string> searchPaths = engine.GetSearchPaths();
            searchPaths.Add(@"C:\Users\abc\CSharp\PythonScriptExecution1\packages\IronPython.2.7.9\lib");
            searchPaths.Add(@"C:\Users\abc\PycharmProjects\untitled3\venv\Lib");
            engine.SetSearchPaths(searchPaths);

            engine.CreateScriptSourceFromFile("C:/Users/abc/PycharmProjects/untitled3/test.py");
            pythonScript.Execute();
        }
    }
}

Upvotes: 1

Related Questions