IronPython 与 c# 交互测试程序

5 篇文章 0 订阅
这个程序只是一个简单测试,在前两个文本框里输入数字,在最后一个文本框里出现结果,只不过是调的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,但是格式一点都不能错,不然就会执行失败,好在出错提示不是一些似是而非的东西,比较容易找到错误根源

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值