我一直试图在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();
它给了我错误:
No module named numpy
如何解决这个问题,谢谢。
IronPython是在.Net运行时之上的一个Python实现。它只能导入和使用纯Python编写的模块,或者是随IronPython本身分发的标准库的一部分。据我所知,numpy不是其中之一,它是一个基于C的扩展。
我希望您安装了一些其他基于C的Python实现(常规的CPython、Anaconda或其他东西),然后在其中添加了numpy,您正试图从IronPython调用它。那是不可能的。
最好将Python脚本保存在一个.py文件中,然后将其作为参数传递给Python.exe并检索结果。你可以用普通的.Net来实现这一点,寻找从C#运行任何exe的方法。
相关问题 更多 >
编程相关推荐