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