【问题标题】:setup ironpython: Module not found设置 ironpython:找不到模块
【发布时间】:2019-07-18 16:59:36
【问题描述】:

我第一次使用 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 脚本的其他方法?

【问题讨论】:

  • ironpython需要下载numpy。 -> stackoverflow.com/a/34630229/2315752 祝你好运,我做不到。
  • 谢谢,但我也无法让它工作......
  • 很抱歉,我们找到的解决方案是直接将Process中的脚本调用到python.exe,所以最后就像从cmd调用脚本一样。有一些解决方法可以传递参数并从流程类接收输出。
  • 顺便说一句,在您尝试之前,Pythonnet 为我们提供了相同的结果。

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


【解决方案1】:

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

【讨论】:

  • 它不起作用...我调整了你正在运行的代码,但错误是一样的
猜你喜欢
  • 2016-12-03
  • 2016-12-18
  • 1970-01-01
  • 2015-09-06
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 2022-12-15
  • 2022-01-16
相关资源
最近更新 更多