直接一段代码演示
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 Files\Python\Python37\Lib");
lstPath.Add(@"D:\Program Files\IronPython 2.7\Lib");
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类函数调用
}