public ScriptOutputStream(ScriptOutput gui, ScriptEngine engine) { _gui = gui; _engine = engine; _gui.txtStdOut.KeyPress += KeyPressEventHandler; _gui.txtStdOut.KeyDown += KeyDownEventHandler; _gui.Closing += ClosingEventHandler; _gui.Closed += ClosedEventHandler; _gui.txtStdOut.Focus(); _completedLines = new Queue<MemoryStream>(); _inputBuffer = new MemoryStream(); _bomCharsLeft = 3; //0xef, 0xbb, 0xbf for UTF-8 (see http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding) }
/// <summary> /// Run the script and print the output to a new output window. /// </summary> public int ExecuteScript(string source) { try { var engine = IronPython.Hosting.Python.CreateEngine(); ScriptScope scope; SetupEnvironment(engine, out scope); var scriptOutput = new ScriptOutput(); scriptOutput.Show(); var outputStream = new ScriptOutputStream(scriptOutput, engine); scope.SetVariable("__window__", scriptOutput); engine.Runtime.IO.SetOutput(outputStream, Encoding.UTF8); engine.Runtime.IO.SetErrorOutput(outputStream, Encoding.UTF8); engine.Runtime.IO.SetInput(outputStream, Encoding.UTF8); var script = engine.CreateScriptSourceFromString(source, SourceCodeKind.Statements); try { script.Execute(scope); _message = (scope.GetVariable("__message__") ?? "").ToString(); return (int)(scope.GetVariable("__result__") ?? Result.Succeeded); } catch (SystemExitException) { // ok, so the system exited. That was bound to happen... return (int)Result.Succeeded; } catch (Exception exception) { // show (power) user everything! _message = exception.ToString(); return (int)Result.Failed; } } catch (Exception ex) { _message = ex.ToString(); return (int)Result.Failed; } }