这个程序只是一个简单测试,在前两个文本框里输入数字,在最后一个文本框里出现结果,只不过是调的python的脚本运算
using IronPython.Hosting;
using Microsoft.Scripting;
using System;
using System.Windows.Forms;
namespace IronPython
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TextBox[] ArrayTB = new TextBox[3];
ArrayTB[0] = textBox1;
ArrayTB[1] = textBox2;
ArrayTB[2] = textBox3;
var py = @"def test():
a = float(ArrayTB[0].Text)
b = float(ArrayTB[1].Text)
c = a + b;
return c";
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
//把c#里的变量赋给python脚本
scope.SetVariable("ArrayTB", ArrayTB);
var code =
engine.CreateScriptSourceFromString(py, SourceCodeKind.InteractiveCode).Compile().Execute(scope);
//调用python脚本里的函数
var adder = scope.GetVariable<Func<double>>("test");
textBox3.Text = adder() + "";
}
}
}
python对代码的格式非常严格,但函数体没有括号,只靠缩进来表示
var py = @"def test():
a = float(ArrayTB[0].Text)
b = float(ArrayTB[1].Text)
c = a + b;
return c";
因此这段字符串虽然是python,但是格式一点都不能错,不然就会执行失败,好在出错提示不是一些似是而非的东西,比较容易找到错误根源