当前位置:首页 > C# > 正文

C#与Python的进程间通信(小白也能看懂的跨语言IPC实战教程)

在现代软件开发中,经常需要不同编程语言编写的程序协同工作。比如用 C# 开发 Windows 桌面应用,而用 Python 处理数据分析或机器学习任务。这时,C#与Python的进程间通信(IPC)就显得尤为重要。本教程将带你从零开始,掌握几种实用的跨语言进程通信方法,即使是编程新手也能轻松上手!

为什么需要 C# 与 Python 通信?

C# 在 Windows 平台上拥有强大的 GUI 和系统集成能力,而 Python 则在数据科学、AI 领域表现卓越。通过Python进程间通信与 C# 结合,可以发挥两者优势,构建功能更强大的混合系统。

C#与Python的进程间通信(小白也能看懂的跨语言IPC实战教程) C#进程间通信 Python进程间通信 C#与Python通信 跨语言进程通信 第1张

方法一:标准输入输出(stdin/stdout)

这是最简单直接的方式。C# 启动 Python 进程,并通过标准输入向其发送数据,再从标准输出读取结果。

Python 端代码(worker.py)

import sysimport jsondef process_data(data):    # 示例:将接收到的字符串转为大写并返回    return data.upper()if __name__ == "__main__":    try:        # 从标准输入读取一行        input_line = sys.stdin.readline().strip()        if input_line:            result = process_data(input_line)            # 将结果以 JSON 格式输出            print(json.dumps({"result": result}))            sys.stdout.flush()  # 确保立即输出    except Exception as e:        print(json.dumps({"error": str(e)}))        sys.stdout.flush()  

C# 端代码

using System;using System.Diagnostics;using System.IO;class Program{    static void Main()    {        var startInfo = new ProcessStartInfo        {            FileName = "python",            Arguments = "worker.py",            UseShellExecute = false,            RedirectStandardInput = true,            RedirectStandardOutput = true,            CreateNoWindow = true        };        using (var process = Process.Start(startInfo))        {            // 向 Python 发送数据            process.StandardInput.WriteLine("hello from csharp");            process.StandardInput.Close();            // 读取 Python 的输出            string output = process.StandardOutput.ReadToEnd();            Console.WriteLine($"Python 返回: {output}");            process.WaitForExit();        }    }}  

方法二:命名管道(Named Pipes)

命名管道适合需要持续双向通信的场景。Windows 原生支持命名管道,C# 可使用 NamedPipeServerStream,Python 可通过 win32pipe(需安装 pywin32)实现。

C# 服务端

using System;using System.IO;using System.IO.Pipes;using System.Text;class PipeServer{    static void Main()    {        using (var server = new NamedPipeServerStream("MyPipe", PipeDirection.InOut))        {            Console.WriteLine("等待客户端连接...");            server.WaitForConnection();            // 读取 Python 发来的消息            byte[] buffer = new byte[1024];            int bytesRead = server.Read(buffer, 0, buffer.Length);            string received = Encoding.UTF8.GetString(buffer, 0, bytesRead);            Console.WriteLine($"收到: {received}");            // 回复消息            string response = "Hello from C#!";            byte[] responseBytes = Encoding.UTF8.GetBytes(response);            server.Write(responseBytes, 0, responseBytes.Length);        }    }}  

Python 客户端(需 pip install pywin32)

import win32pipe, win32file, pywintypesdef connect_to_pipe():    try:        handle = win32file.CreateFile(            r'\\.\pipe\MyPipe',            win32file.GENERIC_READ | win32file.GENERIC_WRITE,            0, None,            win32file.OPEN_EXISTING,            0, None        )                # 发送消息        message = "Hi from Python!"        win32file.WriteFile(handle, message.encode('utf-8'))                # 读取回复        result, data = win32file.ReadFile(handle, 1024)        print(f"C# 回复: {data.decode('utf-8')}")                win32file.CloseHandle(handle)    except Exception as e:        print(f"错误: {e}")if __name__ == "__main__":    connect_to_pipe()  

方法三:HTTP REST API(推荐用于复杂系统)

对于大型项目,建议使用 HTTP 协议。例如,用 Flask 启动一个 Python Web 服务,C# 通过 HttpClient 调用接口。这种方式解耦性强,易于调试和扩展,是工业级C#进程间通信的常用方案。

总结

本文介绍了三种实现 C#与Python通信 的方法:标准输入输出、命名管道和 HTTP API。初学者可从 stdin/stdout 入手,进阶项目推荐使用 RESTful API。无论选择哪种方式,关键在于明确通信需求、数据格式和错误处理机制。

提示:确保 Python 环境已正确安装,并在 C# 项目中添加必要的引用(如 System.IO.Pipes)。