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

    结果如下:

  • 相关阅读:
    HCIA-Storage:第五章 常用存储协议介绍
    HCIA-Storage:SAN基础业务配置和使用:IPSAN,FCSAN
    RH2288v3常用的知识
    不常见的RAID,RAID2,RAID4,RAID7
    华为存储设备管理ip修改
    HCIA-Storage:第七章存储可靠性
    HCIA-Storage:第四章存储系统结构
    SSH服务见解
    shell学习笔记之正则表达式
    shell学习笔记之crontab
  • 原文地址:https://www.cnblogs.com/cysisu/p/10312893.html
Copyright © 2011-2022 走看看