我正在构建一个可以使用 IronPython 自动化的 C# WebKit Web 浏览器,以帮助进行质量保证测试。我将使用 IronPython 创建测试计划,该计划将运行许多浏览器方法、提供参数并评估结果。
IronPython 的大部分文档都说明了如何使用 C# 调用 IronPython 方法,但我已经弄清楚了如何为方法设置参数,以及如何检索方法返回值,但不是从同一个方法。您将在下面的示例中注意到,我将参数传递给一个方法,该方法又设置一个类成员变量,然后使用另一个方法检索该值。
谁能推荐一个更优雅的模式?
using System; using System.Windows.Forms; using IronPython.Hosting; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; namespace PythonScripting.TestApp { public partial class Form1 : Form { private ScriptEngine m_engine = Python.CreateEngine(); private ScriptScope m_scope = null; //used to call funcs by Python that dont need to return vals delegate void VoidFunc(string val); public Form1() { InitializeComponent(); } private void doSomething() { MessageBox.Show("Something Done", "TestApp Result"); } private string _rslt = ""; private string getSomething() { return _rslt; } private void setSomething(string val) { _rslt = val; } private void Form1_Load(object sender, EventArgs e) { m_scope = m_engine.CreateScope(); Func<string> PyGetFunction = new Func<string>(getSomething); VoidFunc PySetFunction = new VoidFunc(setSomething); m_scope.SetVariable("txt", txtBoxTarget); m_scope.SetVariable("get_something", PyGetFunction); m_scope.SetVariable("set_something", PySetFunction); } private void button1_Click(object sender, EventArgs e) { string code = comboBox1.Text.Trim(); ScriptSource source = m_engine.CreateScriptSourceFromString(code, SourceCodeKind.SingleStatement); try { source.Execute(m_scope); Func<string> result = m_scope.GetVariable<Func<string>>("get_something"); MessageBox.Show("Result: " + result(), "TestApp Result"); } catch (Exception ue) { MessageBox.Show("Unrecognized Python Error\n\n" + ue.GetBaseException(), "Python Script Error"); } } } }