首页 > 技术文章 > c#调用python代码

cysisu 2019-01-24 10:10 原文

   c#调用python的方法比较多,比如ironpython,尽管不用安装python环境,可是不兼容python众多的包,也只更新到了python2,通过创建python进程这种方式可以很好的解决兼容性问题。

    创建python进程需要安装python环境,事实上就是通过python执行的结果,返回给c#.这种比较适合用python写算法,c#来做可视化界面,可以实现程序算法和UI分离,也减少了工作量,程序的可读性也会增强。

   借鉴了这一个网站:https://codefying.com/2015/10/02/executing-a-python-script-from-a-c-program/

   下面是python代码:

#!/usr/bin/env

import sys


def main():
    if len(sys.argv) >= 3:
        x = sys.argv[1]
        y = sys.argv[2]
        # print concatenated parameters
        print(x+y)


if __name__ == '__main__':
    main()

   c#代码如下:(根据创建python文件的路径和python.exe的路径去做对应部分的修改)

using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;

namespace ExecutingPythonScript
{
    class EntryPoint
    {
        static void Main(string[] args)
        {

            int x = 1;
            int y = 2;
            string progToRun = "‪E:\\hello1.py";
            char[] spliter = { '\r' };

            Process proc = new Process();
            proc.StartInfo.FileName = "E:/install smallsize software/python3.6.5/python.exe";
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.UseShellExecute = false;

            // call hello.py to concatenate passed parameters
            proc.StartInfo.Arguments = string.Concat("E:/hello1.py", " ", x.ToString(), " ", y.ToString());
            proc.Start();

            StreamReader sReader = proc.StandardOutput;
            string[] output = sReader.ReadToEnd().Split(spliter);

            foreach (string s in output)
                Console.WriteLine(s);

            proc.WaitForExit();

            Console.ReadLine();
        }
    }
}

 

结果如下:

 

推荐阅读