1、C#中新建项目

C#中调用python脚本_System

2、安装IronPython

C#中调用python脚本_开发语言_02

C#中调用python脚本_开发语言_03

3、拷贝python文件

写一个测试的python文件
1.1.py

def test(hellostr):
return (hellostr)

在debug下新建一个pythonfile文件夹,把py文件丢进去

C#中调用python脚本_System_04

C#中调用python脚本_python_05

4、添加一个RunPython.cs类

C#中调用python脚本_Python_06


RunPython.cs

using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace ConsoleApplication2
{
internal class RunPython
{
public void RunPythonTest()
{
// 加载外部 python 脚本文件.
ScriptRuntime pyRumTime = Python.CreateRuntime();
dynamic obj = pyRumTime.UseFile("./pythonfile/1.1.py");

// ==================================================
// 简单调用脚本文件中的方法.

Console.WriteLine(obj.test("这是python中输出的"));
Console.ReadKey();

}
}
}

5、修改程序入口

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication2;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("开始测试Python脚本");
RunPython RunPython = new RunPython();
RunPython.RunPythonTest();
}
}
}

6、测试运行

C#中调用python脚本_开发语言_07