IronPython unable to run script that imports numpy

家住魔仙堡 提交于 2021-02-07 09:36:28

问题


Disclaimer - I'm not familiar with Python. I'm a C# developer who has written an application to execute Python scripts (authored by others) using IronPython. These scripts have so far have only needed to use import math, but one of our users has asked for the application to support for Numpy.

I have installed Numpy on my PC (using the 'numpy-1.9.2-win32-superpack-python2.7.exe' file), which has created a numpy folder under \Lib\site-packages. I've written a two-line Python script to test that Numpy is accessible:-

import numpy as np
x = np.array([1,2])

I run the script from within C#:-

var engine = Python.CreateEngine();
engine.SetSearchPaths(new Collection<string>(new[]
{
    @"C:\Python27", 
    @"C:\Python27\DLLs", 
    @"C:\Python27\Lib", 
    @"C:\Python27\Lib\site-packages", 
    @"C:\Python27\Lib\site-packages\numpy",
    @"C:\Python27\Lib\site-packages\numpy\core"
}));
var scope = engine.CreateScope();
var scriptSource = engine.CreateScriptSourceFromString(
    _myPythonScript, 
    SourceCodeKind.Statements);
scriptSource.Execute(scope);

Despite setting all those search paths, the last line throws an ImportException:-

cannot import multiarray from numpy.core

Note that this SO article is similar, but didn't help - the first answer mentions an 'mtrand.dll' file, which I don't seem to have.

What am I missing?


回答1:


You hit the main limitation of IronPython - it does not support C-API of CPython. Hence you need to use pythonnet:

https://github.com/pythonnet/pythonnet

You can try pure python implementation of numpy:

https://github.com/wadetb/tinynumpy




回答2:


"multiarray" is a .pyd file, and unless someone can correct me, it appears that these aren't supported by IronPython (How can I import a .PYD module in IronPython?).



来源:https://stackoverflow.com/questions/30299837/ironpython-unable-to-run-script-that-imports-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!