C#中调用python脚本
原创
©著作权归作者所有:来自51CTO博客作者wx5e58bcc91c29e的原创作品,请联系作者获取转载授权,否则将追究法律责任
1、C#中新建项目
2、安装IronPython
3、拷贝python文件
写一个测试的python文件
1.1.py
def test(hellostr):
return (hellostr)
在debug下新建一个pythonfile文件夹,把py文件丢进去
4、添加一个RunPython.cs类
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、测试运行