• python与C#交互大汇总


    最近由于写了很多机器学习的代码,所有使用python进行分析,然后将python生成的数据与C#进行数据交互,所以需要通过文件调用的方式,实现起来一波三折,花费了很大的精力。

    1、C#调用python(exe)文件:

      通过C#调用exe文件,进行数据交互,通过C#传参数给python,然后python将计算的结果传递给C#,通过Process调用具体文件,如下所示:

                string cmdpath = AppDomain.CurrentDomain.BaseDirectory + "\\Program\\***.exe";
                if (!File.Exists(cmdpath))
                {
                    MessageBox.Show("无法找到计算程序" + cmdpath);
                    return;
                }
                //LauchPing();
                using (Process p = new Process())
                {
                    p.StartInfo.FileName = cmdpath;
                    p.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory + "\\Program\\";
                    p.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
                    p.StartInfo.RedirectStandardOutput = true;//捕获输出的消息
                    p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
                    p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
                    p.StartInfo.CreateNoWindow = true;//不显示程序窗口
                    p.StartInfo.StandardErrorEncoding = Encoding.UTF8;//将编码设置成utf-8,保证中文不会乱码。
                    p.Start();//启动程序
                    Thread.Sleep(500);              
                    p.StandardInput.WriteLine(strinput);
                    p.StandardInput.WriteLine("exit");
                    p.StandardInput.AutoFlush = true;
    
             }

        获取输出结果

     1                string strresult = p.StandardOutput.ReadToEnd();
     2                 if(strresult==null)
     3                 {
     4                     MessageBox.Show("运算超时");
     5                     return;
     6                 }
     7                 var output = strresult.Split(new char[2] { '\r', '\n' });
     8                 var res = output[0].Split(' ');
     9                 if (res.Length != 19)
    10                 {
    11                     MessageBox.Show("计算结果错误" + output);
    12                     return;
    13                 }
    14                 p.WaitForExit();
    15                 p.Close();    

    2、py文件转为exe文件,在文件转换时,由于自己环境问题,弄了很长时间,主要是环境变量和python文件

      (1)cmd无法识别“pip”、“pyinstaller”等命令;

        

        由于系统环境变量设置问题,无法识别上述命令,修改环境变量。在系统盘的AppData文件夹由于隐藏属性关系无法查看,需要通过绝对路径去访问,查看该路径下的local         Romming路径下的Scripts文件夹,将2个路径下的该文件夹路径设置到环境变量中。

               

            (2)cmd可识别pip,但是无法识别pyinstaller命令,由于local路径不存在pyinstaller.exe文件导致,所以需要将Roaming路径下的文件复制过去,即可使用pyinstaller。pyinstaller具体使用的命令格式为pyinstaller -F C:\***.py(文件绝对路径)

        

         (3)2个路径的如下所示:

      

  • 相关阅读:
    WeTagger不封号的微信客服工具(一)——预告
    WeSender不封号的微信群发软件(六)——升级:第六版已经完成
    .net core系列(一)
    .net core系列整理收藏
    Ansible Windows模块学习
    Windows配置Ansible Host
    Alembic管理Sqlite3数据库版本
    高端VIPRION实物图
    Calendar 类 set() 方法使用要点
    Java 日期处理工具类
  • 原文地址:https://www.cnblogs.com/yxxblog/p/16359680.html
Copyright © 2020-2023  润新知