我一直试图在C#.Net环境中运行python。它成功编译并运行python脚本而无需导入任何库。但是,我需要在C#.Net中运行的python脚本中导入numpy才能正确执行它。 这是我的源代码,没有导入库并且成功:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using IronPython.Hosting;
using Microsoft.CSharp.RuntimeBinder;
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the text you would like the script to print!");
var script =
"class MyClass:\r\n" +
" def __init__(self):\r\n" +
" pass\r\n" +
" def go(self, input):\r\n" +
" print('From dynamic python: ' + input)\r\n" +
" return input";
try
{
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
var ops = engine.Operations;
engine.Execute(script, scope);
var pythonType = scope.GetVariable("MyClass");
dynamic instance = ops.CreateInstance(pythonType);
var value = instance.go(input);
Console.WriteLine(value);
}
catch (Exception ex)
{
Console.WriteLine("Oops! There was an exception" +
" while running the script: " + ex.Message);
}
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
但是,当我尝试导入numpy时:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using IronPython.Hosting;
using Microsoft.CSharp.RuntimeBinder;
namespace TestProject
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the text you would like the script to print!");
var script =
"import numpy" //I added this module
"class MyClass:\r\n" +
" def __init__(self):\r\n" +
" pass\r\n" +
" def go(self, input):\r\n" +
" print('From dynamic python: ' + input)\r\n" +
" return input";
try
{
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
var ops = engine.Operations;
engine.Execute(script, scope);
var pythonType = scope.GetVariable("MyClass");
dynamic instance = ops.CreateInstance(pythonType);
var value = instance.go(input);
Console.WriteLine(value);
}
catch (Exception ex)
{
Console.WriteLine("Oops! There was an exception" +
" while running the script: " + ex.Message);
}
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
它给了我错误:
没有名为numpy的模块
如何解决这个问题,谢谢。
答案 0 :(得分:1)
IronPython是.Net运行时之上的Python实现。它只能导入和使用用纯Python编写的模块,或者是用IronPython本身分发的standardlib的一部分。据我所知,numpy不是其中之一,它是基于C的扩展。
我希望你安装了一些其他基于C语言的Python实现(常规的CPython,Anaconda或其他),然后添加了numpy,你试图从IronPython中调用它。这是不可能的。
您可以做的最好的事情是将Python脚本保存在.py文件中,然后将其作为参数传递给python.exe并检索结果。您可以使用常规.Net来实现这一点,寻找从C#运行任何exe的方法。