zoukankan      html  css  js  c++  java
  • c#(IronPython)调用Python方法

    直接一段代码演示

     public void StartTCP()
            {
                ScriptEngine engine = Python.CreateEngine();
                var paths = engine.GetSearchPaths();
                List<string> lstPath = new List<string>();
                lstPath.AddRange(paths);
                lstPath.Add("Script");
               // lstPath.Add(@"D:Program FilesPythonPython37Lib");
                lstPath.Add(@"D:Program FilesIronPython 2.7Lib");
                engine.SetSearchPaths(lstPath.ToArray());
                var scope = engine.CreateScope();
                var source = engine.CreateScriptSourceFromFile("Script/TCPClsClient.py");
                 dynamic result= source.Execute(scope);
                //调用函数的2种方法
                // 第一种,通过参数方式转换委托调用,看起来不太简洁
                var  SetAddress = scope.GetVariable<Action<string,int>>("SetAddress");
                var Con = scope.GetVariable<Action>("Connect");
                var SendData = scope.GetVariable<Action<string>>("Send");
                var Revcive = scope.GetVariable<Action>("Revcive");
                var Close = scope.GetVariable<Action>("Close");
                SetAddress("localhost", 7777);
                Con();
                SendData("jinyu");
                Revcive();
                Close();
                //第二种,没有智能化提示,必须要转换为dynamic
                result = scope;
                result.SetAddress(result, "localhost", 7777);
                result.Connect();
                result.Send("jinyu");
                result.Recvice();
                result.Close();
                //因为是2.7版本,所以不能支持3.X版本的类方法调用
                //例如: result= scope.GetVariable("TCPClsClient");//调用构造,返回实例
                //result.SetAddress(result, "localhost", 7777);//不能执行,版本不支持3.X类函数调用
            }


     

  • 相关阅读:
    【pandas实战】时间差计算
    【pandas实战】数据分类整理
    海量数据处理方法整理记录
    Springboot中实现策略模式+工厂模式
    实现一个秒杀系统
    Redis实现的分布式锁和分布式限流
    实现分布式服务注册及简易的netty聊天
    聊聊数据库乐观锁和悲观锁,乐观锁失败后重试
    聊聊RPC原理二
    聊聊kafka结构
  • 原文地址:https://www.cnblogs.com/jinyu20180311/p/10501749.html
Copyright © 2011-2022 走看看