Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Python Code in .NET Environment without Installing Python

Is it possible to productionize Python code in a .NET/C# environment without installing Python and without converting the Python code to C#, i.e. just deploy the code as is?

I know installing the Python language would be the reasonable thing to do but my hesitation is that I just don't want to introduce a new language to my production environment and deal with its testing and maintenance complications, since I don't have enough manpower who know Python to take care of these issues.

I know IronPython is built on CLR, but don't know how exactly it can be hosted and maintained inside .NET. Does it enable one to treat PYthon code as a "package" that can be imported into C# code, without actually installing Python as a standalone language? How can IronPython make my life easier in this situation? Can python.net give me more leverage?

like image 732
FatihAkici Avatar asked Jun 24 '19 20:06

FatihAkici


People also ask

Can you run Python without installing Python?

py2exe is a Python extension which converts Python scripts (. py) into Microsoft Windows executables (.exe). These executables can run on a system without Python installed. It is the most common tool for doing so.

Can .NET run 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 you run a PyInstaller exe without Python?

They do not need to have Python installed at all. The output of PyInstaller is specific to the active operating system and the active version of Python. This means that to prepare a distribution for: a different OS.


1 Answers

As I mentioned in the comments, the right and better way to do it is to create Restful services over your Python code and make http-requests from the C# code. I don't know how much you know about web-frameworks in Python but there are tons of them that you can use. For your need, I would suggest Flask which is light-weight micro web-framework to create Restful web services.

This is very simple Flask web-service for the example: (you can check a running version of it here, I hosted it on pythonOnEverywhere)

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello from Flask!'

@app.route('/math/add/<int:num1>/<int:num2>')
def add(num1, num2):
    return '%d' % (num1+num2)

This simple service, adds two number and returns the sum of them.

And C# Code:

using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    // Always use HttpClient as a singleton object
    public static HttpClient _httpClient = new HttpClient() { BaseAddress = new Uri("http://al1b.pythonanywhere.com") } ;
    public async static Task Main()
    {

        var num1 = 1;
        var num2 = 4;

        Console.WriteLine("Making http-request wait ...\r\n");      

        var mathAddResult = await _httpClient.GetAsync($"/math/add/{num1}/{num2}");

        // 200 = OK
        if(mathAddResult.StatusCode == HttpStatusCode.OK)
        {   
            Console.WriteLine(await mathAddResult.Content.ReadAsStringAsync());
        }
    }
}

The output:

Making http-request wait ... 

5

The running version of code above is now runnable on .NET Fiddle.

TL;DR:

For understanding and learning Flask, take a look on its documentions. (It's short and well). I'm sure you will have complex web-services, such as accepting complex or pocco objects as your web-service inputs and returning complex objects (as json) as web-serivce results.

In that case you need to know how Flask jsonify works, This link will tell you how.

Ok, on the other hand, in your C# application you will have those complex objects and scenarios as well. You need to know how to serialize, deseriaze and etc.

Microsoft did a great job for its tutorials here:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

and

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8

like image 165
Ali Bahrami Avatar answered Oct 02 '22 19:10

Ali Bahrami