1、新建项目

2 、安装IronPython
工具-NuGet程序管理器 输入IronPython ;勾选项目后点击安装
安装后,自动添加了引用

3、新建一个文本文件,将后缀名改为“.py”命名为“mytest”
- def main(i,j):
- try:
- z=i+j
- return str(z)
- except Exception as err:
- return str(err)
4、调用python脚本
添加2个文本框和一个label,一个按钮

将 .py文件 放到exe可执行文件的个目录下。
后台程序如下:
- using System;
- using System.Windows.Forms;
-
- using IronPython.Hosting;
- using Microsoft.Scripting.Hosting;
-
- namespace WindowsFormsAppCallPython
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- ScriptEngine pyEngine = Python.CreateEngine();//创建Python解释器对象
- dynamic py = pyEngine.ExecuteFile(@"mytest.py");//读取脚本文件
- string dd = py.main(textBox1.Text, textBox2.Text);//调用脚本文件中对应的函数
- label1.Text = dd + "\r\n";
- }
- }
- }
运行结果:
