设置ironpython:找不到模块

时间:2019-02-25 10:02:51

标签: c# python-3.x ironpython system-paths

我第一次使用Ironpython将Python脚本导入C#。我收到错误“没有名为numpy的模块”,但我不知道为什么。我读到我必须将模块的路径添加到python脚本中。这是我的python脚本:

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)

第二条路径是Pycharm中也用作python.exe的项目解释器的路径。

我的C#代码是这样:

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

在Pycharm中运行Python脚本效果很好,但是将其导入C#会导致上述错误。有人可以帮我设置正确的路径吗?

编辑:如果不起作用,是否有人知道用C#运行python脚本的其他方法?

1 个答案:

答案 0 :(得分:0)

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