我使用IronPythonConsoleControl控件创建了一个应该处理Python脚本的应用程序。我想从python脚本中访问一些C#定义的字典。所以,我做了:
...
public partial class Form1 : Form
{
Dictionary<string, string> envPrm = new Dictionary<string, string>();
PythonConsoleControl.IronPythonConsoleControl pythonConsole = null;
public Form1()
{
InitializeComponent();
pythonConsole = new PythonConsoleControl.IronPythonConsoleControl();
pythonConsole.Pad.Host.ConsoleCreated += new PythonConsoleControl.ConsoleCreatedEventHandler(Host_ConsoleCreated);
}
void Console_ConsoleInitialized(object sender, EventArgs e)
{
pythonConsole.Pad.Console.ScriptScope.SetVariable("envprm", envPrm);
}
void Host_ConsoleCreated(object sender, EventArgs e)
{
pythonConsole.Pad.Console.ConsoleInitialized += new PythonConsoleControl.ConsoleInitializedEventHandler(Console_ConsoleInitialized);
}
private void Form1_Load(object sender, EventArgs e)
{
ehConsole.Child = pythonConsole;
envPrm.Add("a", "Mauro");
envPrm.Add("b", "Bete");
}
private void RunScript(string script)
{
ScriptSource scriptSource = pythonConsole.Pad.Console.ScriptScope.Engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements);
try
{
scriptSource.Execute();
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Error processing initializing script. Message: {0}\r\n, Script: {1}", ex.Message, script));
}
}
private void button1_Click(object sender, EventArgs e)
{
RunScript(textBox1.Text);
}
}
}
问题是,当我运行一些引用envprm变量的脚本时,IronPython引擎并不知道这一点。但是,当我运行一些在控制台引用变量的指令时,它可以正常工作。
答案 0 :(得分:0)
是什么,如果你执行这样的代码:
public dynamic Execute(string Expression)
{
return scriptEngine.CreateScriptSourceFromString(Expression).Execute(scriptScope);
}
这对我很有用。