IronPython: Unexpected token 'from' - c#

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.

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.

Call python script from .Net Core using pythonnet

I'm trying to get pythonnet to work in my .Net Core app running on Linux.
I've made a reference to Python.Runtime.dll (which I got from nuget) in my .Net Core project.
My code is:
using System;
using Python.Runtime;
namespace pythonnet_w
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start");
using (**Py.GIL()**) {
// blabla
}
Console.WriteLine("End");
}
}
}
I get this runtime error:
Unhandled Exception: System.MissingMethodException: Method not found: 'System.Reflection.Emit.AssemblyBuilder
System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)'.
at Python.Runtime.CodeGenerator..ctor()
at Python.Runtime.DelegateManager..ctor()
at Python.Runtime.PythonEngine.Initialize(IEnumerable`1 args, Boolean setSysArgv)
at Python.Runtime.PythonEngine.Initialize(Boolean setSysArgv)
at Python.Runtime.PythonEngine.Initialize()
at Python.Runtime.Py.GIL()
at pythonnet_w.Program.Main(String[] args) in D:\Development\~.Net libraries (3.part)\phytonnet\.Net Core test (phytonnet)\c#\pythonnet_test\Program.cs:line 10
/usr/sbin/pythonnet_w: line 5: 19487 Aborted dotnet "/usr/share/pythonnet_wit/pythonnet_w.dll"
Tried to find a solution in these threads but without any luck:
How do I run a py file in C#?
Call Python from .NET
UPDATE:
I tried to open \pythonnet-master\src\runtime**Python.Runtime.csproj** in Visual Studio to see if I can compile it to .Net or .Core, but I can only compile to .Net framework.
I found this article "How to port from .net framework to .net standard"
Is that what I have to do?
I finally had success by using a self-compiled Python.Runtime.dll as of version 2.4.0. There are two options to create a working DLL:
Remove the other target framework net461 from the respective project file (leaving only netstandard2.0).
Run dotnet build using the appropriate options
For option 2, the following works(in Windows, Mac and Linux):
Clone the pythonnet repo (https://github.com/pythonnet/pythonnet)
In the pythonnet folder, cd src\runtime
Run dotnet build -c ReleaseWinPY3 -f netstandard2.0 Python.Runtime.15.csproj in Windows(in Mac/Linux, replace ReleaseWinPY3 with ReleaseMonoPY3 because the former use python37 and the later use python3.7)
Set DYLD_LIBRARY_PATH in Mac or LD_LIBRARY_PATH in linux(Windows skip):
export DYLD_LIBRARY_PATH=/Library/Frameworks/Python.framework/Versions/3.7/lib
Use the built DLL bin\netstandard2.0\Python.Runtime.dll as DLL reference in your Visual Studio .NET Core project (mine targets netcoreapp2.2, netcoreapp3.1 is also tested ok), e.g. in conjunction with the following code,
using System;
using Python.Runtime;
namespace Python_CSharp
{
class Program
{
static void Main(string[] args)
{
using (Py.GIL())
{
dynamic os = Py.Import("os");
dynamic dir = os.listdir();
Console.WriteLine(dir);
foreach (var d in dir)
{
Console.WriteLine(d);
}
}
}
}
}
You can host the IronPython interpreter right in your .NET application. For example, using NuGet, you can download the right package and then embed the script execution (actually the IronPython engine) right into your application.
Ref:
https://medium.com/better-programming/running-python-script-from-c-and-working-with-the-results-843e68d230e5

Hosting PowerShell core remoting in dot net core app? Has anyone made it work yet?

I've been trying for a month now to host powershell core remoting scripts, that use SSH protocol for remoting, in a dot net core application and so far nothing worked. One of my main issues is that AddScript method of system management automation seems to be doing absolutely nothing when you have Powershell remoting scripts in the block.
I was wondering if anyone has actually tried to host remoting scripts in dot net core C# application successfully?
I actually have an issue raised in the PowerShell github page, but no one is interested in it, hence the zero comments.
https://github.com/PowerShell/PowerShell/issues/7984
Thank you for your help.
I might have found a simple workaround that I've tested and it works.
Basically instead of asking the don net application to call the remoting script via .AddScript method you ask the dot net app to call a local powershell process that executes the remoting script. The script file should be somewhere on the server you're executing the application from. To show this as a code I'm using the following.
string script = "start-process pwsh-preview" -argument "path to script file"
using (Runspace runspace = RunspaceFactory.CreateRunspace())
using (Powershell powershell = Powershell.Create())
{
runspace.Open();
PSCommand command = new PSCommand();
command.AddScript(script);
powershell.Commands = command;
powerhell.Runspace = runspace;
Collection<PSObject> results = new Collection<PSObject>();
results = powershell.Invoke();
I'm yet to test calling the script with parameters (not sure how to do it yet maybe someone here can help). As well as hosting in docker container the entire thing. Most likely PowerShell core will need to be installed as well as dot net core in the docker image for it to work.
Hope this help.
I'm still waiting for the GitHub PowerShell guys to look at the issue.
I will post more information here once I test hosting this in docker.
I struggled getting PS scripts to work through my app as well and made it work just a like a week ago.
Here I launch a script on a remote computer to make a Windows Toast Notification to pop up. You might have to download and install the Powershell.SDK NuGet package for the PowerShell scripts to work.
Here you can see I also get the output generated from the script.
For some reason Verbose output was not captured even though verbose preference was set in the script. I had to capture the output by putting the statements in quotation marks like this:
"OS Version: $OsVersion"
using System;
using System.Diagnostics;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WindowsToasts
{
public class WindowsToast
{
public void Send_WindwsUpdateToast(string computerName)
{
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;
using Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState);
runspace.Open();
using PowerShell powerShell = PowerShell.Create(runspace);
string PSPath = #"C:\temp\ToastText.ps1";
powerShell.AddCommand("Invoke-Command");
powerShell.AddParameter("ComputerName", computerName);
powerShell.AddParameter("File", PSPath);
Collection<PSObject> PSOutput = powerShell.Invoke();
foreach (PSObject outputItem in PSOutput)
{
// if null object was dumped to the pipeline during the script then a null object may be present here
if (outputItem != null)
{
Debug.WriteLine($"Output line: [{outputItem}]");
}
}
}
}
}

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

how to import python 3 libraries in iron python

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

Categories

Resources