C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#调用Python代码的方式

在C#中调用Python代码的两种实现方式

作者:学亮编程手记

这篇文章主要介绍了在C#中调用Python代码的两种实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

C#调用Python代码的方式

在 C# 中调用 Python 代码有几种不同的方法。

一种常用的方法是使用 Python.NET 库,它允许你在 C# 中直接调用 Python 代码。另一种方法是使用外部进程调用 Python 脚本,例如通过 Process.Start

下面是两种主要方法的详细介绍:

1. 使用 Python.NET

安装 Python.NET

首先,你需要安装 Python.NET。可以通过 NuGet 包管理器来安装:

Install-Package Python.Runtime

示例代码:

接下来,让我们看看如何使用 Python.NET 在 C# 中调用 Python 代码。

using System;
using Python.Runtime;

namespace CSharpPythonIntegration
{
    class Program
    {
        static void Main(string[] args)
        {
            // 初始化 Python 运行时
            using (Py.GIL())
            {
                // 加载 Python 模块
                dynamic pyModule = Py.Import("your_python_module");

                // 调用 Python 函数
                dynamic result = pyModule.YourFunctionName(args);

                Console.WriteLine($"Result from Python: {result}");
            }
        }
    }
}

注意事项:

2. 使用外部进程调用 Python 脚本

如果你不想使用 Python.NET,你可以通过创建一个进程来运行 Python 脚本。

示例代码:

下面是一个简单的例子,演示如何使用 System.Diagnostics.Process 类来运行 Python 脚本。

using System;
using System.Diagnostics;

namespace CSharpPythonIntegration
{
    class Program
    {
        static void Main(string[] args)
        {
            string pythonScriptPath = @"C:\path\to\your\script.py";
            string pythonExePath = @"C:\Python39\python.exe"; // Python 解释器路径

            ProcessStartInfo startInfo = new ProcessStartInfo(pythonExePath, pythonScriptPath)
            {
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };

            using (Process process = new Process())
            {
                process.StartInfo = startInfo;
                process.Start();

                // 读取 Python 脚本的输出
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                Console.WriteLine($"Output from Python script: {output}");
            }
        }
    }
}

注意事项:

这两种方法都可以实现在 C# 中调用 Python 代码的目标,但是 Python.NET 提供了更紧密的集成,而使用外部进程则更加简单直接,适用于简单的调用场景。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文