C#操作动态语言----Python
2014-09-24 23:17
197 查看
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("你好猎人")); } } }
****需要库的去我的下载里面去下载
相关文章推荐
- 如何用Python,C#等语言去实现抓取静态网页+抓取动态网页+模拟登陆网站
- 如何用Python,C#等语言去实现抓取静态网页+抓取动态网页+模拟登陆网站
- 如何用Python,C#等语言去实现抓取静态网页+抓取动态网页+模拟登陆网站
- Javascript、C#、php、asp、python 等语言的链式操作的实现
- python是动态语言的表现以及属性方法操作
- 【转载】[翻译整理]使用RAPI库操作移动设备——C#语言描述
- C#动态生成WORD文档并进行操作。
- dynamic lookup将变得很强大,推导出很多动态语言特性,这是C#团队的功劳
- 使用C#语言操作ADO数据库
- 使用C#语言操作ADO数据库
- C# 动态语言扩展(学习笔记)
- c#语言操作Access数据库
- 动态语言Ruby、Python源码对比分析日记(一)
- python 的一些思考(字符,django,动态语言)
- Python和Ruby:流行动态脚本语言之特点对比
- c#语言asp.net实现treeview控件读数据库动态生成树的代码
- C#动态生成WORD文档并进行操作
- 在emacs开启几个动态语言的shell(perl, python, ruby, bean shell,groovy)
- C#动态操作SQL的方法!
- C#对动态语言的支持