C# for Python(Nugut Iron包)
cInronPython是一种在.NET和Mono上实现的Python语言,使用InronPython就可以在.NET环境中调用Python代码
安装InronPython
Python:
port sys reload(sys) sys.setdefaultencoding('utf8') def Test1(para1,para2): return para1+para2; def Test2(): return '求求你们别学了'
C#:
var pythonEngine = Python.CreateEngine();//(options); var pyText = Convert.ToBase64String(File.ReadAllBytes(new FileInfo(@"F:\Practice\net\py\PYTest1\PYTest1\Test2.py").ToString())); var CodeString = Encoding.UTF8.GetString(Convert.FromBase64String(pyText)); `读取文件 方法一` var script = pythonEngine.CreateScriptSourceFromString(CodeString); `读取文件 方法二` //var script = pythonEngine.CreateScriptSourceFromFile(@"F:\Practice\net\py\PYTest1\PYTest1\Test2.py"); var code = script.Compile(); var scope = pythonEngine.CreateScope(); var excuteResult = code.Execute(scope); //调用py方法,不带参数 //var _func = scope.GetVariable("Test2"); //var CustomerData = _func(); //调用py方法,带参数 var _func = scope.GetVariable("Test1"); var CustomerData = _func(1,2); Console.WriteLine(CustomerData); Console.ReadKey();