how to import python 3 libraries in iron python - c#

I am trying to call a python script on a button click of an exe built with C#.
I installed the following dll's
using System.Windows.Forms;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
and myscript.py is
import sys
sys.path.append("C:\ProgramData\Anaconda3\Lib")
import os
print (os.getcwd())
import pandas as pd
print("hi")
my c# code:
private static void doPython()
{
ScriptEngine engine = Python.CreateEngine();
engine.ExecuteFile(#"test.py");
Console.WriteLine();
}
I get unexpected token 'from' error when running my solution, please help. thanks in advance

Related

Trying to get powershell working within C#/Visual Studio

I was trying to learn how to use powershell within C#
I was following this tutorial
However when I run it I get this error:
Unhandled exception. System.InvalidProgramException: Common Language Runtime detected an invalid program.
at System.Management.Automation.PowerShell.Create()
at desktopAdmin365.Program.Main(String[] args) in C:\Users\ncox\source\repos\desktopAdmin365\Program.cs:line 11
C:\Users\ncox\source\repos\desktopAdmin365\bin\Debug\netcoreapp3.0\desktopAdmin365.exe (process 17464) exited with code -532462766.
I am sure I'm missing something when including references/dependencies from the solutions explorer but I am not having any luck with google finding out which one
Here is the code
using System;
using System.Management.Automation;
using System.Collections.ObjectModel;
namespace desktopAdmin365
{
class Program
{
static void Main(string[] args)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; " +
"$d; $s; $param1; get-service");
}
}
}
}
If you look at your dependencies in the project, you'll likely see a warning about the package being restored using .NETFramework and possibly not being compatible.
Your project is .NET core, so you might need to install Powershell Core instead.
https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-windows?view=powershell-6
Alternatively, switch to a .net framework solution and it will work.

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 *

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

Getting python script linked with C#

I am using Visual Studio 2017 with NuGet packages: IronPython installed.
I need to be able to get the python script working in the C# application without an end user having to install python. I can get basic applications to run without any problem by just IronPython, then I tested with the library I needed for the script to work and it no longer worked with just IronPython and it would then need to point at my python Lib folder in order to get the libraries it needs. Is there any way around this or is the end user going to have no choice but to install python and the library on their computer to get my application to work?
Code for reference:
using IronPython.Hosting;
namespace testApp {
class Program {
static void Main(string[] args) {
var py = Python.CreateEngine();
try {
py.ExecuteFile(#"python\test.py");
}
catch (Exception ex) {
Console.WriteLine(ex.Message + " - Error from visual studio");
}
Console.Read();
}
}
}
Python:
import sys
sys.path.append(r"C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\Lib") # points to python interpreter
import os
from reportlab.pdfgen import canvas
c = canvas.Canvas("Test.pdf")
c.drawString(100, 100, "This is some test text!")
c.showPage()
c.save()

IronPython: Unexpected token 'from'

i was running python script from .net using IronPython, below is my python script
import tensorflow as tf
print('Tensorflow Imported')
below is C# Code
using System;
using System.Text;
using System.IO;
using IronPython.Hosting;
using System.Collections.Generic;
using Microsoft.Scripting.Hosting;
namespace ConsoleApplication1
{
class Program
{
private static void Main()
{
var py = Python.CreateEngine();
List<string> searchPaths = new List<string>();
searchPaths.Add(#"C:\Users\Admin\AppData\Local\Programs\Python\Python35\Lib)");
searchPaths.Add(#"C:\Users\Admin\AppData\Local\Programs\Python\Python35\Lib\site-packages)");
py.SetSearchPaths(searchPaths);
try
{
py.ExecuteFile("script.py");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
below is my output
Unexpected token 'from'
if i remove import statement then python script executes fine. I tried including os,sys all those were imported without any issue. I have installed TensorFlow via pip, when i run above script through python console(v3.5) it works fine.
Update: in TF doc its written "TensorFlow only supports version 3.5.x of Python on Windows". but official release of IronPython is version 2.7
I was happy to find IronPython on GitHub, tried building it (i just typed build in console and got freaked out with the long list of error messages it showed! :D
couldn't find pre-compiled binaries
is there any alternative way to import tensorflow in IronPython 2.7 or run Python in .net?
Prakash - as you found in the documentation, TensorFlow requires Python 3.5 or 3.6 when running on Windows. It won't run in IronPython 2.7.
One user on GitHub successfully (with a lot of work and in a not-easy-to-do) way got TF running on Windows under Python2.7, and you might be able to build on their work, but it's not exactly the solution you were looking for for IronPython. My best suggestion is to go with 3.5 or 3.6.

Categories

Resources