需要在Nuget安装IronPython, 如果报错,需要更新Nuget版本则下载对应版本即可:https://dist.nuget.org/index.html

添加引用:IronPython.dll,Microsoft.Scripting.dll(在IronPython的安装目录中)

c#文件:

  1. using IronPython.Hosting;
  2. using Microsoft.Scripting.Hosting;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. namespace PythonDemo
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. ScriptRuntime pyRunTime = Python.CreateRuntime();
  14. dynamic obj = pyRunTime.UseFile("hello.py");
  15. Console.WriteLine(obj.welcome("Nick"));
  16. Console.WriteLine(obj.add(1,3));
  17. Console.ReadKey();
  18. }
  19. }
  20. }

python文件:

  1. #hello.py
  2. def welcome(name):
  3. return "hello " + name
  4. def add(a,b):
  5. return a+b

运行结果: