Import Numpy Package for IronPython - c#

So I'm building an app using C# that requires calling a python script which needs to import numpy. My python version is 3.6 and I am running IronPython 2.7 (64-bit). This is the error I'm getting. "Original error was: cannot import multiarray from numpy.core". Is there any way I can reference Numpy? I've looked everywhere and I genuinely cannot find a solution. The enthought solution is no longer available from previous answers. This is my code.
ScriptRuntime scriptRuntime = Python.CreateRuntime();
ScriptEngine scriptEngine = scriptRuntime.GetEngine("py");
var paths = scriptEngine.GetSearchPaths();
paths.Add(#"C:\Users\minhaj\source\Workspaces\Python\PythonProject\env\Lib");
paths.Add(#"C:\Users\minhaj\source\Workspaces\Python\PythonProject\env\Lib\site-packages");
paths.Add(#"C:\Program Files (x86)\IronPython 2.7\Lib");
scriptEngine.SetSearchPaths(paths);
dynamic pythonScript = scriptRuntime.UseFile(path);
dynamic pythonMethod = pythonScript.hello();

Related

How to install modules to IronPython in VisualStudio

I need to use Python code in the C# application. So I decide to install IronPython NuGet to my project in VisualStudio. When I try to run the script, I always have errors with the Python Modules (like numpy, json...).
I tried solutions like include path to the folder with modules.
# first try
var ipy = Python.CreateRuntime();
dynamic test = ipy.UseFile("some.py");
test.Test();
# error 1
IronPython.Runtime.Exceptions.ImportException: 'No module named numpy'
# the tried this
var engine = Python.CreateEngine();
var paths = engine.GetSearchPaths();
paths.Add(...pathToModules);
engine.SetSearchPaths(paths);
dynamic logging = engine.ImportModule("numpy");
#error 2
Microsoft.Scripting.SyntaxErrorException: 'unexpected token 'append''
I'm using Anaconda with Spyder, python version 3.5. The problem isn't about python version.
Can you help me please to solve it? It's possible to install some modules to the IronPython in VisualStudio environment?

Import issue with IronPython and Visual Studio 2015

I want to integrate IronPython in my .NET C# Library but I have always the following exception
Additional information: No module named 'modulename'
In my C# library project, I've installed the following IronPython NuGet
Install-Package IronPython
Install-Package IronPython.StdLib
Python simple code (getLogScaledPNG.py):
import numpy as np
import matplotlib.pyplot as plt
def getLogScaledPNG(filename):
data = plt.imread(filename);
data[data == 0.] = np.nan;
logdata = np.log(data);
plt.imsave("logimage.png", logdata, cmap="gray");
print 'Scaled Image Saved'
C# code:
using IronPython.Hosting;
var ipy = Python.CreateRuntime();
dynamic getLogScaledPNG = ipy.UseFile(#".\PythonScripts\getLogScaledPNG.py");
getLogScaledPNG.getLogScaledPNG("toto.png");
When I execute this C# code, I've got the following Exception:
Additional information: No module named numpy
I don't understand where and how can I add this module ?
I just have the reference to the IronPython DLLs in my .NET project and I haven't got any folders where I can add this module
In addition to the IronPython DLLs, you need Python standard library scripts.
Download IronPython.StdLib.2.7.8.zip, extract everything to a folder
And add this to your code:
ScriptEngine engine = Python.CreateEngine();
var searchPaths = engine.GetSearchPaths();
searchPaths.Add(#"C:\yourLibFolder");
engine.SetSearchPaths(searchPaths);

pythonnet Embedding Python in .net example failing to load module

I'm trying to run the Embedding Python in .NET example from https://github.com/pythonnet/pythonnet. I've followed troubleshooting articles to set the proper %PYTHONPATH% and %PYTHONHOME% to my anaconda environment in the program base directory.
After activating my anaconda environment, I have successfully imported sys, and imp as a test, and also sucessfully used PythonEngine.RunSimpleString(), but the numpy example fails with Python.Runtime.PythonException: ImportError : No module named 'numpy'
importing numpy from python in this environment was successful, but this and other packages fail to import in pythonnet.
Pythonnet version: 2.3 x64 (installed using conda install -c pythonnet pythonnet)
Python version: Python 3.5 x64 (anaconda)
Operating System: Windows 10
The following code produces the error:
static void Main(string[] args)
{
string envPythonHome = AppDomain.CurrentDomain.BaseDirectory + "cntk-py35";
string envPythonLib = envPythonHome + #"\Lib";
Environment.SetEnvironmentVariable("PYTHONHOME", envPythonHome, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PATH", envPythonHome + ";" + Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine), EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONPATH", envPythonLib, EnvironmentVariableTarget.Process);
PythonEngine.PythonHome = envPythonHome;
PythonEngine.PythonPath = Environment.GetEnvironmentVariable("PYTHONPATH");
using (Py.GIL())
{
dynamic np = Py.Import("numpy");
Console.WriteLine(np.cos(np.pi * 2));
dynamic sin = np.sin;
Console.WriteLine(sin(5));
double c = np.cos(5) + sin(5);
Console.WriteLine(c);
dynamic a = np.array(new List<float> { 1, 2, 3 });
Console.WriteLine(a.dtype);
dynamic b = np.array(new List<float> { 6, 5, 4 }, dtype: np.int32);
Console.WriteLine(b.dtype);
Console.WriteLine(a * b);
Console.ReadKey();
}
}
It seems that any package under site-packages in my environment similarly fail. Adding to %PATH% did not work. Is there a way to get pythonnet to recognize and load these modules?
Setting up your python environment in .NET is a bit cumbersome.This issue is not well detailed on pythonnet website or most of suggested solutions I have found on the internet did not work for my computer. The reason is that every computer may have a different python setup environment (depending how you have installed python and the libraries). It took me a while as well but finally I have succeeded to call python modules and .py scripts from .NET. Here is what I did.
Pythonnet version: 2.4.0 x64 (installed using pip install # Anaconda CMD prompt)
Python version: Python 3.7 x64 (Anaconda)
Operating System: Windows 10
Keep in mind that everyone has a different Python environment, that is why you have to configure your environment first (in your VS project).
First, we need to assign "PATH", "PYTHONHOME" and "PYTHONPATH" variables.
in C# use:
string pythonPath1 = #"C:\Users\<your username>\Anaconda3";
string pythonPath2 = #"C:\Users\<your username>\Anaconda3\lib\site-packages";
Environment.SetEnvironmentVariable("PATH", pythonPath1, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONHOME", pythonPath1, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONPATH", pythonPath2, EnvironmentVariableTarget.Process);
I have used Anaconda to install python runtime and packages. Note that default Anaconda installation is under C:\Users(your username assigned in your computer)\Anaconda3. (You can find yours using code by (How can I get the current user directory?). If you did not use Anaconda, you need to locate the directory where python packages are installed on your computer.
1-C:\Users\\Anaconda3 directory must have your version of python DLL (i.e.python37.dll).
2-C:\Users\\Anaconda3\lib\site-packages has the "modules" (i.e. python frameworks like 'numpy').
3-You must reference python runtime in your project (Python.Runtime.dll).(use Windows File Explorer to find the file. If you use Anaconda the runtime is under C:\Users\\Anaconda3 directory).
4-Add following on top of your code:
using Python.Runtime;
5-In VS Solution Explorer right click on your project and select 'Properties'
and make sure to set 'Platform Target' (either x64 or x86)
6-After doing all this, if you can NOT run some of the 'modules' and receive a "Can not load module" or "can not find module" exception message, then follow the instruction here (https://github.com/microsoft/vscode-python/issues/9218)
Usually, uninstalling/re-installing the module will resolve the issue by updating the version. (i.e. pip uninstall numpy/pip install numpy).
NOTE: The code still works, even if you do not set PYTHONPATH variable above. PYTHONPATH variable is used, when you need to call a custom .py script, where you identify the directory where your file resides. A descriptive example can be found at https://stackoverflow.com/a/57910578/7675537
UPDATE: I have realized that one easy way to configure your Python Environment is using Visual Studio (I use VS 2017 Community version). Just go to Python in Visual Studio and go through the example. In VS under 'Python Environments' you can observe all the setups you have in your computer. I had problems to run .py scripts, like not being able to use 'import matplotlib.pyplot' and spent several hours reading articles on the internet but could not find a solution. Finally I switched my environment to 'C:\Users\\AppData\Local\Programs\Python\Python37\' and installed all the missing packages from visual studio's list (of suggestions) and it worked. I think calling Anaconda environment from .NET (via pythonnet or else) has problems. I would suggest not to use your Anaconda python environment if you make .NET calls to python. I use:
private static string pythonPath1 = #"C:\Users\<your name>\AppData\Local\Programs\Python\Python37";
static void Main(string[] args)
{
Test();
}
private static void Test()
{
string pathToPython = pythonPath1;
string path = pathToPython + ";" +
Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine);
Environment.SetEnvironmentVariable("PATH", path, EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable("PYTHONHOME", pathToPython, EnvironmentVariableTarget.Process);
var lib = new[]
{
#"C:\Users\<your name>\<your python code is here>",
Path.Combine(pathToPython, "Lib"),
Path.Combine(pathToPython, "DLLs")
};
string paths = string.Join("; ", lib);
Environment.SetEnvironmentVariable("PYTHONPATH", paths, EnvironmentVariableTarget.Process);
using (Py.GIL()) //Initialize the Python engine and acquire the interpreter lock
{
try
{
// import your script into the process
dynamic sampleModule = Py.Import("yourpythoncode");
}
catch (PythonException error)
{
Console.WriteLine("Error occured: ", error.Message);
}
}
}
I was able to import the modules by adding Lib/site-packages to the PYTHONPATH variable (rather than the PATH) which adds the folder to sys.path. It was necessary for any other python libraries and custom python code to add the corresponding folder to PYTHONPATH.

Trying to understand how to include 3rd party modules in IronPython

I am using IronPython within VS2010. I am new to both Python and IronPython.
I have a Python script that imports cx_Oracle.
When I execute my script Main.py, I get an error that module cx_Oracle is not found.
My C# code looks like this:
public void MyMethod(string input)
{
var engine = Python.CreateEngine();
List<string> libPath = new List<string>();
libPath.Add(#"C:\Program Files (x86)\IronPython 2.7\Lib\site-packages");
engine.SetSearchPaths(libPath);
var scope = engine.CreateScope();
var eng = engine.ExecuteFile(Script, scope);
var myResult = scope.GetVariable("myInputVar");
var result = myResult(input);
}
I installed the cx_oracle module and it placed the files in my Python\site-packages folder. I then copied those same files over to the equivalent in my IronPython directory which I reference in the SetSearchPaths.
What am I missing?
Install the package manager pip by downloading this python script: https://bootstrap.pypa.io/get-pip.py
Open a command prompt and run
python get-pip.py
After install run:
pip install cx_Oracle
Or if you need to manage multiple python environments at once check out anaconda: http://docs.continuum.io/anaconda/install
EDIT: For Ipython
Install pip:
ipy -X:Frames -m ensurepip
install cx_Oracle
ipy -X:Frames -m pip install cx_Oracle

"No module named fcntl" when py script run from c# but works from windows command line

I am calling a python script that uses imaplib.py and get the "no module named fcntl" error. From searching I found that this module is only available in unix and so I wonder if the py script is confused about what os it is running under. Again, script works fine under windows run directly from the python directory.
var engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
var ops = engine.Operations;
var script = engine.CreateScriptSourceFromFile("PyTest.py");
CompiledCode code = script.Compile();
//string scode = script.GetCode();
code.Execute(scope);
and the minimal py script to trigger it. Note that commenting out the import imaplib.py line will stop the error.
import sys
sys.path = ["Python\Lib"]
sys.platform = ["win32"]
import os
import os
import getopt
import getpass
import time
import imaplib
I traced it a bit to the subprocess.py that imaplib.py uses, there I noticed the sys.platform variable and tried setting it to win32 as above but made no difference. Something is different between the ironpython calling environment and the windows command prompt from the cpython folder.
First of all you're setting sys.platform to a list, it should be a string. .NET/CLI is a different platform than Win32 though, so just setting sys.platform won't help.
Some Googling suggests IronPython doesn't support the subprocess module (or the module doesn't support IronPython). There is a partial replacement here: http://www.ironpython.info/index.php?title=The_subprocess_module
There's also a bugreport with some discussion here: http://bugs.python.org/issue8110
The Microsoft distribution does not load the standard library by default.
You have to set the path in your code in order to access it.
The easiest way to do it is to create an environment variable called "IRONPYTHONPATH" which contains the path to the Lib folder of the IronPython installation.
Once you have created it, you can read the location as follows:
from System import Environment
pythonPath = Environment.GetEnvironmentVariable("IRONPYTHONPATH")
import sys
sys.path.append(pythonPath)
More details here.
http://www.ironpython.info/index.php/Using_the_Python_Standard_Library

Categories

Resources