public Dictionary <string, object> Run() { foreach (string varKey in this.pythonVars.Keys.ToArray()) { this.pyScope.SetVariable(varKey, this.pythonVars[varKey]); } try { this.lastError = ""; this.pySource.Execute(this.pyScope); if (this.pySource.GetCode() == "") { System.Diagnostics.Debug.Write("Warning: no source code"); this.lastError = "Warning: no source code\n"; } } catch (Exception ex) { System.Diagnostics.Debug.Write("Error: "); System.Diagnostics.Debug.WriteLine(ex.Message); ExceptionOperations eo = this.pyEngine.GetService <ExceptionOperations>(); this.lastError = eo.FormatException(ex); } foreach (string varKey in this.pythonVars.Keys.ToArray()) { this.pythonVars[varKey] = this.pyScope.GetVariable(varKey); } return(this.pythonVars); }
/// <summary> /// Loads the script /// </summary> /// <param name="scriptPath">The script path.</param> public void LoadScript(string scriptPath) { if (!loadedScripts.ContainsKey(scriptPath)) { try { ScriptSource src = _engine.CreateScriptSourceFromFile(scriptPath); CompiledCode code = src.Compile(); ApplicationScript cpy = new ApplicationScript(scriptPath, code, _scope); loadedScripts.Add(scriptPath, cpy); ScriptEventHandler handler = this.ScriptLoaded; if (handler != null) { handler(cpy); } } catch (SyntaxErrorException ex) { ExceptionOperations eo = _engine.GetService <ExceptionOperations>(); string error = eo.FormatException(ex); string msg = "Syntax error in \"{0}\"{1}Details:{1}{2}"; msg = string.Format(msg, Path.GetFileName(scriptPath), Environment.NewLine, error); MessageService.ShowError(msg); } } }
public void RunFile(string path, Action <Exception> handleException = null) { if (!File.Exists(path)) { return; } //Environment.CurrentDirectory = Path.GetDirectoryName(Path.GetFullPath(path)); //var lines = File.ReadAllLines(path); //RunPy(lines); var source = engine.CreateScriptSourceFromFile(path); try { object result = source.Execute(scope); } catch (Exception x) { handleException?.Invoke(x); if (handleException == null) { Console.Error.WriteLine($"Error Executing Script"); ExceptionOperations eo = engine.GetService <ExceptionOperations>(); string error = eo.FormatException(x); Console.Error.WriteLine(error); var inner = x; while (inner != null) { Console.Error.WriteLine($"[{inner.GetType().Name}] {inner.Message}"); Console.Error.WriteLine(inner.StackTrace); inner = inner.InnerException; } } } }
/// <summary> /// Executes the given file</summary> /// <param name="fileName">Full file path</param> /// <returns>Script output text</returns> public string ExecuteFile(string fileName) { string result = string.Empty; try { FileInfo finfo = new FileInfo(fileName); if (!finfo.Exists) { throw new FileNotFoundException(finfo.FullName); } ScriptSource source = m_engine.CreateScriptSourceFromFile(finfo.FullName); source.Execute(m_scope); result = m_stream.Text; } catch (Exception ex) { ExceptionOperations eo = m_engine.GetService <ExceptionOperations>(); result = m_stream.Text + eo.FormatException(ex); } m_stream.Reset(); return(result); }
/// <summary> /// Main method /// </summary> /// <param name="args">Command line args.</param> public static void Main(string[] args) { engine = Python.CreateEngine(); scope = engine.CreateScope(); engine.Runtime.LoadAssembly(typeof(TurntableBot).Assembly); engine.Runtime.LoadAssembly(typeof(JObject).Assembly); engine.Runtime.IO.RedirectToConsole(); ScriptSource source = null; if (File.Exists(Script)) { source = engine.CreateScriptSourceFromFile(Script); } else { Console.WriteLine("File not found"); } if (source != null) { try { source.Execute(scope); } catch (Exception e) { ExceptionOperations ops = engine.GetService <ExceptionOperations>(); Console.WriteLine(ops.FormatException(e)); } } Console.ReadLine(); }
public void HandleException(Exception ex) { ExceptionOperations eo = _scriptEngine.GetService <ExceptionOperations>(); string error = eo.FormatException(ex); Engine.Services.Get <Logger>().LogEvent($"Script error: {error}", LogTypes.ERROR, ex); }
public void showError(string title, string name, Exception e) { string caption = String.Format(title, name); ExceptionOperations eo = _engine.GetService<ExceptionOperations>(); string error = eo.FormatException(e); MessageBox.Show(error, caption, MessageBoxButton.OK, MessageBoxImage.Error); }
public void Execute(IEnumerable <string> cmd, Func <Exception, bool> handleException = null, bool stopOnError = true) { var e = cmd.GetEnumerator(); while (e.MoveNext()) { scope.RemoveVariable("clr"); var source = engine.CreateScriptSourceFromString(e.Current); try { object result = source.Execute(scope); } catch (Exception x) { if (handleException == null) { Console.Error.WriteLine($"Error Executing Script"); ExceptionOperations eo = engine.GetService <ExceptionOperations>(); string error = eo.FormatException(x); Console.Error.WriteLine(error); var inner = x; while (inner != null) { Console.Error.WriteLine($"[{inner.GetType().Name}] {inner.Message}"); Console.Error.WriteLine(inner.StackTrace); inner = inner.InnerException; } } var doContinue = handleException?.Invoke(x) ?? !stopOnError; if (!doContinue) { return; } } } }
public void FormatException_Test() { ScriptEngine engine = _runtime.GetEngine("py"); ExceptionOperations es = engine.GetService <ExceptionOperations>(); OutOfMemoryException e = new OutOfMemoryException(); string result = es.FormatException(e); Assert.AreNotEqual(e.Message, result); }
protected virtual void UnhandledException(ScriptEngine engine, Exception e) { Console.Error.Write("Unhandled exception"); Console.Error.WriteLine(':'); ExceptionOperations es = engine.GetService <ExceptionOperations>(); Console.Error.WriteLine(es.FormatException(e)); }
public DynamicExceptionInfo(Exception e) { ContractUtils.RequiresNotNull(e, "e"); _exception = e; _dynamicStackFrames = ScriptingRuntimeHelpers.GetDynamicStackFrames(e); // We can get the file name and line number from either the // DynamicStackFrame or from a SyntaxErrorException SyntaxErrorException se = e as SyntaxErrorException; if (null != se) { _sourceFileName = se.GetSymbolDocumentName(); _sourceLine = se.Line; } else if (_dynamicStackFrames != null && _dynamicStackFrames.Length > 0) { _sourceFileName = _dynamicStackFrames[0].GetFileName(); _sourceLine = _dynamicStackFrames[0].GetFileLineNumber(); } // Try to get the ScriptEngine from the source file's extension; // if that fails just use the current ScriptEngine ScriptEngine engine = null; try { if (_sourceFileName != null) { var extension = System.IO.Path.GetExtension(_sourceFileName); _runtime.TryGetEngineByFileExtension(extension, out engine); } else { throw new Exception(); } } catch { if (DynamicApplication.Current.Engine != null) { engine = DynamicApplication.Current.Engine.Engine; } } // If we have the file name and the engine, use ExceptionOperations // to generate the exception message. Otherwise, create it by hand if (_sourceFileName != null && engine != null) { ExceptionOperations es = engine.GetService <ExceptionOperations>(); es.GetExceptionMessage(_exception, out _message, out _errorTypeName); } else { _errorTypeName = _exception.GetType().Name; _message = _errorTypeName + ": " + _exception.Message; } }
private string ExecuteStatement(string statement, bool multiStatements) { string result = string.Empty; if (string.IsNullOrEmpty(statement)) { return(result); } try { SourceCodeKind sourceKind = multiStatements ? SourceCodeKind.Statements : SourceCodeKind.SingleStatement; ScriptSource source = m_engine.CreateScriptSourceFromString(statement, sourceKind); // JAL - 7/18/2012 - // // If you are running from the debugger and see the following: // // An exception of type 'IronPython.Runtime.Exceptions.ImportException' occurred in IronPython.Modules.dll // and wasn't handled before a managed/native boundary // // Additional information: not a Zip file // // and if this exception occurs during application initialization (trying to import python modules, e.g. from system import * // then here are some notes that may help: // // - you may safely continue through these exceptions, and possibly disable them with a debugger setting. // - this behavior only occurs when running from the debugger // - behavior started when upgrading from IronPython 2.6 to 2.7.3 // - the exception is part of normal Python flow control, and is related to loading modules from zip files // - In VS2010: Tools/Options -> Debugging/General --> set a check on option "just my code" // - note: this alters the appearance of "Debug/Exceptions" menu // - note: unfortunately didn't work for me, but worked for everyone else. // - will update this comment when resolved. // // UPDATE: Ron disabled the zipimport feature as a more reliable workaround (see BasicPythonService.cs) // source.Execute(m_scope); result = m_stream.Text; } catch (Exception ex) { ExceptionOperations eo = m_engine.GetService <ExceptionOperations>(); result = m_stream.Text + eo.FormatException(ex); } m_stream.Reset(); return(result); }
/// <summary> /// Execute code and return a dynamic with results. /// </summary> /// <param name="code">String of code to execute.</param> /// <returns>Dynamic with result.</returns> public dynamic Execute(string code) { try { dynamic result = engine.Execute(code, scope); return(result); } catch (Exception e) { ExceptionOperations eo = engine.GetService <ExceptionOperations>(); string error = eo.FormatException(e).TrimEnd('\n'); errorWriter.Write(error); return(null); } }
private bool Execute() { try { this._code.Execute(this._scope); return(true); } catch (Exception e) { ExceptionOperations eo = this._engine.GetService <ExceptionOperations>(); System.Diagnostics.Debug.Write(eo.FormatException(e)); return(false); } }
public bool Execute() { try { _code.Execute(_scope); return(true); } catch (Exception e) { ExceptionOperations eo = _engine.GetService <ExceptionOperations>(); Console.Write(eo.FormatException(e)); System.Windows.Forms.MessageBox.Show(eo.FormatException(e), "Python Error", System.Windows.Forms.MessageBoxButtons.OK); return(false); } }
/// <summary> /// Runs the script. /// </summary> /// <param name="scriptPath">The script path.</param> public void RunScript(string scriptPath) { try { ScriptSource src = _engine.CreateScriptSourceFromFile(scriptPath); CompiledCode code = src.Compile(); code.Execute(_scope); } catch (SyntaxErrorException ex) { ExceptionOperations eo = _engine.GetService <ExceptionOperations>(); string error = eo.FormatException(ex); string msg = "Syntax error in \"{0}\"{1}Details:{1}{2}"; msg = string.Format(msg, Path.GetFileName(scriptPath), Environment.NewLine, error); MessageService.ShowError(msg); } }
public void RunRawCode(InputImage[] images, string rawCode) { string pythonCode = this.GetFunctionCode(rawCode); dynamic scope = engine.CreateScope(); try { engine.Execute(pythonCode, scope); } catch (SyntaxErrorException ex) { engine = null; scope = null; ExceptionOperations eo = engine.GetService <ExceptionOperations>(); MessageBox.Show(eo.FormatException(ex)); } if (engine == null || scope == null) { throw new Exception("Cannot create Python engine!"); } ImageExtensions.SaveAction = saveCallback; foreach (var inputImage in images) { Image imageCopy = new Image(inputImage.SourceImage); try { scope.ProcessImage(imageCopy); } catch (Exception ex) { throw new Exception("Error processing " + inputImage.SourceImage.Filename + ": " + ex.Message); } } }
private void ExecuteScript(object sender, UIEventArgs e) { if (e.keyboardState.IsKeyDown(Keys.Enter) && e.lastKeyboardState.IsKeyUp(Keys.Enter)) { OnCommandSubmitted(this, e); //log.Add(inputbox.Text); //from Microsoft.Xna.Framework import *\n StringBuilder userCode = new StringBuilder(); userCode.Append("import clr\nclr.AddReference('IronPython')\nclr.AddReference('MonoGame.Framework')\nclr.AddReference('OpenTK')\nfrom Microsoft.Xna.Framework import *\nfrom IronPython.Hosting import Python\nimport Wartorn\nfrom Wartorn import *\n"); userCode.Append(inputbox.Text); inputbox.Clear(); ScriptSource source = _engine.CreateScriptSourceFromString(userCode.ToString()); CompiledCode code = null; //catch compile error try { code = source.Compile(); } catch (Exception err) { ExceptionOperations eo = _engine.GetService <ExceptionOperations>(); Utility.HelperFunction.Log(eo.FormatException(err) + '\n' + userCode.ToString()); log.Add("error when compile script"); return; } //catch runtim error try { code.Execute(_scope); } catch (Exception err) { ExceptionOperations eo = _engine.GetService <ExceptionOperations>(); Utility.HelperFunction.Log(eo.FormatException(err) + '\n' + userCode.ToString()); log.Add("error when execute script"); } } }
internal static DebugInfo CreateError(Exception ex, ExecutionContext executionScope) { var info = new DebugInfo(); info.ExecutionScope = executionScope; ExceptionOperations eo = info.ExecutionScope.ScriptEngine.GetService <ExceptionOperations>(); string message; string errorTypeName; eo.GetExceptionMessage(ex, out message, out errorTypeName); info.Message = message; info.ErrorTypeName = errorTypeName; var frames = eo.GetStackFrames(ex); info.CurrentLine = frames[0].GetFileLineNumber(); info.IsError = true; return(info); }
/// <summary> /// Returns Python style traceback of the given exception object /// </summary> /// <param name="e">exception handle</param> /// <returns>String representing the traceback information</returns> public object getTraceback(Exception e) { ExceptionOperations eo = Engine.GetService <ExceptionOperations>(); return(eo.FormatException(e)); }
public DynamicExceptionInfo(Exception e) { ContractUtils.RequiresNotNull(e, "e"); _exception = e; if (DynamicApplication.Current != null && DynamicApplication.Current.Engine != null && DynamicApplication.Current.Engine.Engine != null) { _dynamicStackFrames = ArrayUtils.ToArray(DynamicApplication.Current.Engine.Engine.GetService <ExceptionOperations>().GetStackFrames(e)); } // We can get the file name and line number from either the // DynamicStackFrame or from a SyntaxErrorException SyntaxErrorException se = e as SyntaxErrorException; if (null != se) { _sourceFileName = se.GetSymbolDocumentName(); _sourceLine = se.Line; } else if (_dynamicStackFrames != null && _dynamicStackFrames.Length > 0) { _sourceFileName = _dynamicStackFrames[0].GetFileName(); _sourceLine = _dynamicStackFrames[0].GetFileLineNumber(); } // Try to get the ScriptEngine from the source file's extension; // if that fails just use the current ScriptEngine ScriptEngine engine = null; try { if (_sourceFileName != null) { var extension = System.IO.Path.GetExtension(_sourceFileName); _runtime.TryGetEngineByFileExtension(extension, out engine); } else { throw new Exception(); } } catch { if (DynamicApplication.Current.Engine != null) { engine = DynamicApplication.Current.Engine.Engine; } } // If we have the file name and the engine, use ExceptionOperations // to generate the exception message. if (_sourceFileName != null && engine != null) { ExceptionOperations es = engine.GetService <ExceptionOperations>(); es.GetExceptionMessage(_exception, out _message, out _errorTypeName); // Special case error message for needing to upgrade to SL4 } else if (_exception.Message.Contains("Method not found: 'Void System.Threading.Monitor.Enter(System.Object, Boolean ByRef)'")) { _errorTypeName = "Silverlight 4 required"; _message = "Silverlight version error: this Silverlight application requires Silverlight 4 to run, please upgrade."; // Otherwise, create it by hand } else { _errorTypeName = _exception.GetType().Name; _message = _errorTypeName + ": " + _exception.Message; } }
private void AsyncStart() { if (m_Source == null) { return; } if (World.Player == null) { return; } try { m_Source.Execute(m_Scope); } catch (Exception ex) { if (ex is System.Threading.ThreadAbortException) { return; } if (ScriptErrorLog) // enabled log of error { StringBuilder log = new StringBuilder(); log.Append(Environment.NewLine + "============================ START REPORT ============================ " + Environment.NewLine); DateTime dt = DateTime.Now; log.Append("---> Time: " + String.Format("{0:F}", dt) + Environment.NewLine); log.Append(Environment.NewLine); if (ex is SyntaxErrorException) { SyntaxErrorException se = ex as SyntaxErrorException; log.Append("----> Syntax Error:" + Environment.NewLine); log.Append("-> LINE: " + se.Line + Environment.NewLine); log.Append("-> COLUMN: " + se.Column + Environment.NewLine); log.Append("-> SEVERITY: " + se.Severity + Environment.NewLine); log.Append("-> MESSAGE: " + se.Message + Environment.NewLine); } else { log.Append("----> Generic Error:" + Environment.NewLine); ExceptionOperations eo = m_Engine.GetService <ExceptionOperations>(); string error = eo.FormatException(ex); log.Append(error); } log.Append(Environment.NewLine); log.Append("============================ END REPORT ============================ "); log.Append(Environment.NewLine); try // For prevent crash in case of file are busy or inaccessible { File.AppendAllText(Assistant.Engine.RootPath + "\\" + m_Filename + ".ERROR", log.ToString()); } catch { } log.Clear(); } } }
public RubyEngine() { _engine = Ruby.CreateEngine(); _exceptionOperations = _engine.GetService <ExceptionOperations>(); }
internal MacroScriptEngine(string scriptType) { loadRunTime(); m_engine = m_runTime.GetEngine(scriptType); m_exceptionOperations = m_engine.GetService <ExceptionOperations>(); }
public static string GetExceptionMessage(ScriptEngine engine, Exception ex) { ExceptionOperations eo = engine.GetService <ExceptionOperations>(); return(eo.FormatException(ex)); }
static void Main(string[] args) { if (args.Length == 1) { if (args[0].Substring(args[0].Length - 3) == ".py") { // get console output if (!AttachConsole(-1)) { AllocConsole(); } // Run script Console.WriteLine("MeteoInfo Scripting"); frmMain aFrm = new frmMain(true); string aFile = args[0]; ScriptEngine scriptEngine = Python.CreateEngine(); ScriptScope pyScope = scriptEngine.CreateScope(); //Set path string path = Assembly.GetExecutingAssembly().Location; string rootDir = Directory.GetParent(path).FullName; List <string> paths = new List <string>(); paths.Add(rootDir); paths.Add(Path.Combine(rootDir, "Lib")); scriptEngine.SetSearchPaths(paths.ToArray()); pyScope.SetVariable("mipy", aFrm); //Run python script try { //ScriptSource sourceCode = scriptEngine.CreateScriptSourceFromString(text, SourceCodeKind.Statements); ScriptSource sourceCode = scriptEngine.CreateScriptSourceFromFile(aFile); sourceCode.Execute(pyScope); //CompiledCode compiled = sourceCode.Compile(); //compiled.Execute(pyScope); //sourceCode.ExecuteProgram(); } catch (Exception e) { ExceptionOperations eo = scriptEngine.GetService <ExceptionOperations>(); Console.Write(eo.FormatException(e)); } //aFrm.RunScript(aFile); //aFrm.Dispose(); //aFrm.Show(); //Application.Run(aFrm); //aFrm.Close(); FreeConsole(); // detach console // get command prompt back System.Windows.Forms.SendKeys.SendWait("{ENTER}"); } else if (args[0].Substring(args[0].Length - 4) == ".mip") { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); frmMain myApp = new frmMain(); string pFile = args[0]; pFile = Path.Combine(System.Environment.CurrentDirectory, pFile); myApp.OpenProjectFile(pFile); Application.Run(myApp); } } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } }
protected virtual void UnhandledException(Exception e) { ExceptionOperations exceptionOperations = _engine.GetService <ExceptionOperations>(); _console.WriteLine(exceptionOperations.FormatException(e), Style.Error); }
private void AsyncStart() { if (World.Player == null) { return; } try { string fullpath = Path.Combine(Assistant.Engine.RootPath, "Scripts", m_Filename); string ext = Path.GetExtension(fullpath); if (ext.Equals(".uos", StringComparison.InvariantCultureIgnoreCase)) { UOSteamEngine uosteam = new UOSteamEngine(); uosteam.Execute(fullpath); } else { DateTime lastModified = System.IO.File.GetLastWriteTime(fullpath); if (FileChangeDate < lastModified) { ReadText(); FileChangeDate = System.IO.File.GetLastWriteTime(fullpath); Create(null); } /*Dalamar: BEGIN "fix python env" */ //EXECUTION OF THE SCRIPT //Refactoring option, the whole block can be replaced by: // //m_pe.Execute(m_Text); m_Source = m_Engine.CreateScriptSourceFromString(m_Text); // "+": USE PythonCompilerOptions in order to initialize Python modules correctly, without it the Python env is half broken PythonCompilerOptions pco = (PythonCompilerOptions)m_Engine.GetCompilerOptions(m_Scope); pco.ModuleName = "__main__"; pco.Module |= ModuleOptions.Initialize; CompiledCode compiled = m_Source.Compile(pco); compiled.Execute(m_Scope); // "-": DONT execute directly, unless you are not planning to import external modules. //m_Source.Execute(m_Scope); /*Dalamar: END*/ } } catch (IronPython.Runtime.Exceptions.SystemExitException ex) { Stop(); // sys.exit - terminate the thread } catch (Exception ex) { if (ex is System.Threading.ThreadAbortException) { return; } string display_error = m_Engine.GetService <ExceptionOperations>().FormatException(ex); SendMessageScriptError("ERROR " + m_Filename + ":" + display_error.Replace("\n", " | ")); if (ScriptErrorLog) // enabled log of error { StringBuilder log = new StringBuilder(); log.Append(Environment.NewLine + "============================ START REPORT ============================ " + Environment.NewLine); DateTime dt = DateTime.Now; log.Append("---> Time: " + String.Format("{0:F}", dt) + Environment.NewLine); log.Append(Environment.NewLine); if (ex is SyntaxErrorException) { SyntaxErrorException se = ex as SyntaxErrorException; log.Append("----> Syntax Error:" + Environment.NewLine); log.Append("-> LINE: " + se.Line + Environment.NewLine); log.Append("-> COLUMN: " + se.Column + Environment.NewLine); log.Append("-> SEVERITY: " + se.Severity + Environment.NewLine); log.Append("-> MESSAGE: " + se.Message + Environment.NewLine); } else { log.Append("----> Generic Error:" + Environment.NewLine); ExceptionOperations eo = m_Engine.GetService <ExceptionOperations>(); string error = eo.FormatException(ex); log.Append(error); } log.Append(Environment.NewLine); log.Append("============================ END REPORT ============================ "); log.Append(Environment.NewLine); try // For prevent crash in case of file are busy or inaccessible { File.AppendAllText(Assistant.Engine.RootPath + "\\" + m_Filename + ".ERROR", log.ToString()); } catch { } log.Clear(); } } }