您的位置:首页 > 编程语言 > Python开发

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("你好猎人"));
}
}
}

















****需要库的去我的下载里面去下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息