c# - Python 和 C# 之间的通信

标签 c# python .net rpc python.net

我有一个运行机器学习算法的 Python 后端。我想对 Excel 插件 (C#) 和网站使用相同的后端。我希望两个接口(interface)都能将我的训练数据(数组中的数千行数字)发送到同一个 Python 应用程序,并以最多几千行的另一个数组的形式检索结果。

该网站将从 SQL 数据库中获取数据并将该数据发送到 Python,而 Excel 插件将获取当前工作表中的数据并将该数据发送到 Python。在继续处理数据之前,我需要能够在 Python 中创建 numpy 数组。请注意,该网站将在 Python 应用程序所在的同一台机器上运行。我还没有决定我将使用什么来编写网站代码,但我倾向于 Node.js。

我做了一些研究并找到了一些选择:

1- Named pipes
2- Sockets
3- RPC server such as gRPC or XML-RPC.
4- Writing the data to a file and reading it back in Python
5- Web Service

注意:我需要 Python“服务器”是有状态的,并在调用之间保持 session 运行。所以我需要有一种守护进程在运行,等待调用。

专家们会推荐哪一个?为什么?我需要灵 active 来处理多个参数以及大量数字。使用 IronPython 不是一个选项,因为我在 Python 上运行 Keras,它显然不支持 IronPython。

最佳答案

我最近遇到了同样的问题。 我使用命名管道将数据从 python 传输到我的 c# 服务器,希望它对你有帮助。

python :

import win32pipe, win32file

class PipeServer():
    def __init__(self, pipeName):
        self.pipe = win32pipe.CreateNamedPipe(
        r'\\.\pipe\\'+pipeName,
        win32pipe.PIPE_ACCESS_OUTBOUND,
        win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
        1, 65536, 65536,
        0,
        None)
    
    #Carefull, this blocks until a connection is established
    def connect(self):
        win32pipe.ConnectNamedPipe(self.pipe, None)
    
    #Message without tailing '\n'
    def write(self, message):
        win32file.WriteFile(self.pipe, message.encode()+b'\n')

    def close(self):
        win32file.CloseHandle(self.pipe)


t = PipeServer("CSServer")
t.connect()
t.write("Hello from Python :)")
t.write("Closing now...")
t.close()

要使此代码正常工作,您需要安装 pywin32(最好选择二进制文件):https://github.com/mhammond/pywin32

C#-服务器:

using System;
using System.IO;
using System.IO.Pipes;

class PipeClient
{
    static void Main(string[] args)
    {
        using (NamedPipeClientStream pipeClient =
            new NamedPipeClientStream(".", "CSServer", PipeDirection.In))
        {

            // Connect to the pipe or wait until the pipe is available.
            Console.Write("Attempting to connect to pipe...");
            pipeClient.Connect();

            Console.WriteLine("Connected to pipe.");
            Console.WriteLine("There are currently {0} pipe server instances open.",
               pipeClient.NumberOfServerInstances);
            using (StreamReader sr = new StreamReader(pipeClient))
            {
                // Display the read text to the console
                string temp;
                while ((temp = sr.ReadLine()) != null)
                {
                    Console.WriteLine("Received from server: {0}", temp);
                }
            }
        }
        Console.Write("Press Enter to continue...");
        Console.ReadLine();
    }
}

关于c# - Python 和 C# 之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939357/

相关文章:

c# - 如何从 C# 中的 Excel 工作簿中删除工作表?

c# - 为什么当我传递参数时调度程序会这样?

c# - 在 C# 中创建 Websocket 服务器的最简单方法是什么?

python - 用于 Python 编程的 Emacs : module/class outline/browser

python - 如何在 python、odoo 中使用 For 循环正确计数?

python - Matplotlib - 绘制宽度等于一系列值的线,而不仅仅是一个值

c# - 找不到 Windows Phone 7 组合框

c# - 我的第一个WPF应用程序中的WPF window_loaded异常

c# - Excel:如果使用绝对路径只能打开文件,为什么?

java - 如何在 Java 中使用/反序列化 .Net WCF 服务 JSON 响应