C#调用python
转载自 https://www.cnblogs.com/jason2004/p/6182995.html
using System; using IronPython.Hosting; namespace CsharpPython { // E:\test.py: // def say_hello(): // print "hello" // def get_text(): // return "hhh" // def add(arg1, arg2): // return arg1 + arg2 class Program { static void Main(string[] args) { var engine = Python.CreateEngine(); var scope = engine.CreateScope(); var source = engine.CreateScriptSourceFromFile("e:\\test.py"); source.Execute(scope); var say_hello = scope.GetVariable<Func<object>>("say_hello"); say_hello(); var get_text = scope.GetVariable<Func<object>>("get_text"); var text = get_text().ToString(); Console.WriteLine(text); var add = scope.GetVariable<Func<object, object, object>>("add"); var result1 = add(1, 2); Console.WriteLine(result1); var result2 = add("hello ", "world"); Console.WriteLine(result2); Console.ReadKey(); } } }