C#操作动态语言----Python

ususing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using System.IO;
using System.Dynamic;
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
         
        }
        /// <summary>
        /// 计算(引用外部文件)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void but_Compute_Click(object sender, EventArgs e)
        {
            string scriptPath = "";
            if (rbut_Price.Checked)
                scriptPath = Directory.GetCurrentDirectory() + "/a.py";
            else
                scriptPath = Directory.GetCurrentDirectory() + "/b.py";
            //动态语言环境对象
            ScriptRuntime script = Python.CreateRuntime();
            //语言引擎对象
            ScriptEngine engine = script.GetEngine("Python");
            //指定脚本文件
            ScriptSource source = engine.CreateScriptSourceFromFile(scriptPath);
            //创建承载参数的对象
            ScriptScope scope = script.CreateScope();
            //指定参数并设置值
            scope.SetVariable("a", Convert.ToDecimal(txt_Price.Text));
            //执行语句
            source.Execute(scope);
            //show出参数
            lbl_Result.Text = scope.GetVariable("b").ToString();
        }
        /// <summary>
        /// 直接内部计算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //动态对象
            dynamic dyn = new ExpandoObject();
            dyn.name = "猎人";
            ScriptRuntime script = Python.CreateRuntime();
            ScriptEngine engine= script.GetEngine("py");
            ScriptSource source = engine.CreateScriptSourceFromString("dyn.name=‘代号::猎人::‘");
            ScriptScope scope = engine.CreateScope();
            //设置参数
            scope.SetVariable("dyn", dyn);
            //执行
            source.Execute(scope);
            MessageBox.Show(scope.GetVariable("dyn").name);//输出:代号::猎人::
        }
        private void button2_Click(object sender, EventArgs e)
        {
            ScriptRuntime script = Python.CreateRuntime();
            dynamic dyn = script.UseFile(Directory.GetCurrentDirectory() + "/c.py");
            MessageBox.Show(dyn.getValue("你好猎人"));
        }
    }
}

 ****需要库的去我的下载里面去下载

本文出自 “程序猿的家--Hunter” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1557911

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。