Vin*_*t L 8 .net c# python rpc python.net
我有一个运行机器学习算法的 Python 后端。我想对 Excel 插件 (C#) 和网站使用相同的后端。我希望两个接口都将我的训练数据(数组中的数千行数字)发送到同一个 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
Run Code Online (Sandbox Code Playgroud)
注意:我需要 Python“服务器”是有状态的,并在调用之间保持会话运行。所以我需要有一种守护进程在运行,等待调用。
您会推荐哪一种?为什么?我需要灵活地处理多个参数以及大量数字。使用 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()
Run Code Online (Sandbox Code Playgroud)
要使此代码工作,您需要安装 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();
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Python for .NET (Python.NET)。它可能需要对您的代码进行一些更改,但是一旦一切都处于良好状态,它应该可以很好地工作。
Python.NET 允许 CPython 和 CLR 之间的双向通信。
| 归档时间: |
|
| 查看次数: |
17116 次 |
| 最近记录: |