Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IronPython unable to run script that imports numpy

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?

like image 830
Andrew Stephens Avatar asked Jun 28 '26 12:06

Andrew Stephens


1 Answers

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

like image 52
denfromufa Avatar answered Jul 01 '26 02:07

denfromufa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!