问题描述
- 如何在C#中使用IronPython
- 如何在C#中使用IronPython执行Python语句,例如,一个表达式:string expr=""a=1
n def b(): nt print a n b()n"",执行后打印“1”。
解决方案
参考
using System;using System.Windows.Forms;using IronPython.Hosting;using System.Drawing;namespace CSharpAndIpy{ public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); } private void btnRunOfString_Click(object sender EventArgs e) { try { //创建一个IpyRunTime,需要2-3秒时间。建议进入全局时加载,此为演示 var engine = IronPython.Hosting.Python.CreateEngine(); var code = engine.CreateScriptSourceFromString(txtScript.Text); var actual = code.Execute<object>();//执行code脚本,获取输出值actual txtPrint.Text = actual.ToString(); } catch (Exception ex) { txtPrint.Text = ex.ToString(); } } //执行事先准备的my.py脚本 private void btnRunOfIpyFile_Click(object sender EventArgs e) { var engine = Python.CreateEngine(); var scope = engine.CreateScope(); scope.SetVariable(""Ipy_this"" this);//将this Set 到Ipy脚本的Ipy_this值中 var code = engine.CreateScriptSourceFromFile(""my.py"");//执行my.py code.Execute(scope); } /// <summary> /// 测试方法,要为public才能在Ipy脚本中访问 /// </summary> public void testMethod(int Rint Gint B) { try { txtScript.BackColor = Color.FromArgb(R G B); } catch { } } }}
时间: 2024-11-17 23:08:49