Import issue with IronPython and Visual Studio 2015 - c#

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);

Related

Accessing .net core dll using python

I need to access a C# dll which is built in .net core (.NETCore version = v1.1). I tried in the below way but I am getting the import error.
import clr
clr.AddReference("dllname") - No error
from dllname import *
Got Import Error exception saying no module named dllname.
Note: I tried in both Iron python and python both are giving me the same exception.
I'm trying on Fedora 29, using mono 5.18, python3.7 and netcore 3.0.100-preview-009812,
and seems to work if you use absolute paths to resolve the netcore dll
import clr
import os
clr.AddReference(os.path.abspath('./bin/Debug/netstandard2.0/sample.dll'))
import sample
p = sample.Person(name='Peter')
netcore project was generated like that
dotnet new classlib -o sample
Person class
using System;
namespace sample
{
public class Person
{
public string Name { get; set; }
}
}
UPDATE
Based on data provided by #SMHP seems like an incompatibility between main .NET framework/mono (pythonnet runtime) and a library targeting .netcoreapp 2.0.
You get import error because you are using dllname in import statement. Instead of using dllname use namespace of the dll.
P.S: don't use same name for dll and namespace it will throw an error while importing in python
import clr
clr.AddReference("dllname") - No error
from namespace import *

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 Numpy Package for IronPython

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();

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