zoukankan      html  css  js  c++  java
  • c#调用python代码

       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 = { '
    ' };
    
                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();
            }
        }
    }

    结果如下:

  • 相关阅读:
    send和sendmsg性能测试【sendmsg和send的性能基本一样,并没有得到优化】
    send和sendmsg性能测试
    SparkException: Master removed our application
    大数据入门:各种大数据技术介绍
    78 subsets
    C、C ++的内存模型
    将博客搬至CSDN
    适配器模式
    建造者(Builder)模式
    桥接模式
  • 原文地址:https://www.cnblogs.com/cysisu/p/10312893.html
Copyright © 2011-2022 走看看