c#调用python代码

程序使用排名

这两个语言都是非常容易上手和使用的,python作为目前数据处理的主流语言,在数据处理中有一些优势,目前,算法的开发都是在python上,但是项目的代码都是c#,因此为了方便那边大佬的调用,特地的找了下这方面的资料。

方案一,使用ironpython

这个网上搜到的方法,很常见的一个。从官网可以看到,目前最新的是2018年3月更新,支持python2.7,并没有支持python3的版本。由于我们的项目主要是基于python3因此放弃了这条路。

方案二,使用调用进程的方式

编导并不太理解里面的深入原理,过程就是,在c#里面,调用python.exe,运行.py文件。这里就要保证.py文件要把你想要的结果,通过输出流的方式输出出来,’c#’获取输出流,进而进行其他处理。
本文的代码是在linux上的,由于’c#’是跨平台的,如果在windows中,只需要把cmd的值定位本地中的./python.exe即可。要是已经将python设置成了环境变量,就只需要python即可,不需要具体的地址了。
下面是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;

namespace Kindergarten//命名空间,包含若干个类
{
    public class Hello
    {
    static void run_cmd(string cmd,string args)//args是 python 和 .py文件
    {
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = cmd;
        start.Arguments = args;
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.Write(result);
            }
        }
    }

    static void Main(string[] args)//main方法,c#语言的入口
    {
        run_cmd(args[0],args[1]);
    }

    }
}

参考文档

C与python的调用一(导入python模块与,获得函数与类)
深入理解python之类的创建过程
makes pointer from integer without a cast
官方PyObject
python - Linux C调用Python 函数

猜你喜欢

转载自blog.csdn.net/tortelee/article/details/81945894
今日推荐