Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Python in .NET-Core application?

Tags:

How to use Python in .NET-Core application? I need this for the purposes of Hackathon so the solution don't have to be 'elegant'. I've read that it's impassible to run Python scripts directly because there exists only library IronPython for standard ASP.NET but no for .NET-Core. So what is the simplest way to use Python scripts? (Because it's hackathon it's ok to use even PHP server or selenium etc. only to execute script)

like image 720
Maciek Drabicki Avatar asked Dec 09 '16 16:12

Maciek Drabicki


People also ask

Can I use Python in .NET core?

This works fine on windows and with . NET framework compiled binaries.

Can I use .NET with Python?

Python.NET is a package that gives Python programmers nearly seamless integration with the . NET 4.0+ Common Language Runtime (CLR) on Windows and Mono runtime on Linux and OSX. Python for . NET provides a powerful application scripting tool for .

Can we integrate Python with C#?

Python scripts can be executed from C# with IronPython.

How do you call a method in Python C#?

FileName = "python.exe"; startInfo. Arguments = "-c import foo; print foo. hello()"; process.


1 Answers

Try this

public class RunCmd {     public string Run(string cmd, string args)     {         ProcessStartInfo start = new ProcessStartInfo();         start.FileName = "python";         start.Arguments = string.Format("\"{0}\" \"{1}\"", cmd, args);         start.UseShellExecute = false;// Do not use OS shell         start.CreateNoWindow = true; // We don't need new window         start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back         start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)         using (Process process = Process.Start(start))         {             using (StreamReader reader = process.StandardOutput)             {                 string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script                 string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")                 return result;             }         }     } } 

Then

 var res = new RunCmd().Run("your_python_file.py","params");  Console.WriteLine(res); 
like image 149
nimo Avatar answered Sep 29 '22 20:09

nimo