/// <summary> /// Parse a string, executing python code as required. Code snippets should be surrounded by braces, and can /// return any type of value - although if the python class does not implement a sensible <c>__str__</c>, it /// will not make much sense. /// </summary> /// <example> /// (in python) /// <code para="str"> /// variable_a = "foo"; /// variable_b = "bar" /// </code> /// (in c#) /// <code> /// ParseStringForVariable("{variable_a}{variable_b}") //returns "foobar" /// </code> /// </example> /// <param name="str">The string to parse</param> /// <returns> /// String /// </returns> /// <remarks>This has been constructed to be as robust as possible, but as always, doing silly things will /// result in silly things happening. For instance <c>__import__("sys").execute("yes | rm -rf /")</c> will /// do exactly what you expect on a linux machine. However, it has yet to be seen if it is possible to /// break the parser to execute such code without it being clearly visible. /// <para/> /// The end user should always remember to treat jobs as executables, and not to run anything received from /// an untrusted source without carefully checking it over first.</remarks> protected String ParseStringForVariable([NotNull] String str) { OnMessage(MessageLevel.Debug, "Attempting to parse string {0}", str); IPythonEngine pythonEngine = GetCurrentCore().PythonEngine; string orig = str; var expressions = FindPythonExpressions(str); foreach (Expression expression in expressions) { string result = expression.Template; try { this.OnMessage(MessageLevel.Debug, "Python expression found: {0}", expression.Code); dynamic r = pythonEngine.Evaluate(expression.Compiled); result = r.ToString(); this.OnMessage(MessageLevel.Debug, "Expression evaluated to {0}", result); } catch (PythonException e) { this.OnMessage(MessageLevel.Debug, "Expression could not be evaluated: Python raised exception {0}", e.Message); } str = str.Replace(expression.Template, result); //break; } OnMessage(MessageLevel.Debug, "String {0} parsed to {1}", orig, str); return(str); }
private void CreatePythonEngine() { _pythonEngine = new GeoDo.PythonEngine.PythonEngine(); Dictionary <string, object> vars = new Dictionary <string, object>(); vars.Add("session", this); _pythonEngine.SetupEngine(vars); }
/// <summary> /// Perform the action /// </summary> protected override void DoAction() { ParseStringForVariable(this.DestinationVarName); IPythonEngine engine = GetCurrentCore().PythonEngine; var scope = engine.GetNewTypedScope(Variables); Variables[DestinationVarName] = engine.Evaluate <object>(Expresson, scope); }
private dynamic TryEvaluate(String str) { try { IPythonEngine engine = GetCurrentCore().PythonEngine; var evaluated = engine.Evaluate(str); return(evaluated); } catch (PythonException) { return(str); } }
protected String OldParseStringForVariable([NotNull] String str) { IPythonEngine pythonEngine = GetCurrentCore().PythonEngine; Regex expressionRegex = new Regex(@"(?<template>{(?<expression>.*?)})", RegexOptions.ExplicitCapture); MatchCollection matches = expressionRegex.Matches(str); var enumerable = from Match match in matches select(string) pythonEngine.Evaluate(match.Groups[@"expression"].Value).ToString(); string injected = enumerable.Aggregate(str, expressionRegex.Replace); OnMessage(MessageLevel.Core, "String {0} parsed to {1}", str, injected); return(injected); }
/* * public void UpdateSource(object sender, EventArgs e) * { * ScintillaNET.Scintilla control = sender as ScintillaNET.Scintilla; * Source = control.Text; * this._complexity = Source.Split(System.Environment.NewLine.ToCharArray()).Length; * } */ protected override void DoAction() { IPythonEngine engine = GetCurrentCore().PythonEngine; //if (!engine.VariableExists(@"variables")) //{ // engine.SetVariable(@"variables", Variables); //} try { engine.Execute(Source); } catch (PythonException e) { throw new ActionException(e, this); } }
public void NotityFetchLog() { IPythonEngine pyEngine = _session.PythonEngine as IPythonEngine; if (pyEngine != null) { GeoDo.PythonEngine.SimpleLogger.Entry[] items = pyEngine.GetAllLog(); if (items == null || items.Length == 0) { return; } foreach (GeoDo.PythonEngine.SimpleLogger.Entry it in items) { lb.Items.Insert(0, it.msg); } } }
private void OsModuleWorkaround() { IPythonEngine engine = GetCurrentCore().PythonEngine; var progFilesX68 = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86); string pythonLibDir = Path.Combine(progFilesX68, "ironpython 2.7", "lib"); if (!Directory.Exists(pythonLibDir)) { var activeForm = Form.ActiveForm ?? (Form)this.GetCurrentCore().Tag; pythonLibDir = (string)activeForm.Invoke(new Func <string>(this.GetPythonLibDir)); if (String.IsNullOrEmpty(pythonLibDir)) { throw new FatalActionException("Could not find Python Lib folder", this); } } engine.ImportModule("sys"); engine.Execute(string.Format("sys.path.append('{0}')\n", pythonLibDir)); engine.ImportModule("os"); }
/// <summary> /// /// </summary> /// <param name="str"></param> /// <returns></returns> public IEnumerable <Expression> FindPythonExpressions(string str) { // XXX : May break on set literals IPythonEngine pythonEngine = this.GetCurrentCore().PythonEngine; List <Expression> pythonExpressions = new List <Expression>(); foreach (int i in str.IndexesWhere('{'.Equals)) { //string str1 = str; int opening = i; foreach (int closing in str.IndexesWhere('}'.Equals)) { if (closing > opening) { Expression expression = new Expression { Template = str.Substring(opening, closing - opening + 1), // Template is the string between & including opening and closing braces Code = str.Substring(opening + 1, closing - opening - 1), // Code is the bit between the braces, it isn't neccessarily valid pyton Start = opening, End = closing }; PythonParseException parseException; if (!this.Throws(expression.CompileWith, pythonEngine, out parseException)) { // Code is valid pyton //this.OnMessage(MessageLevel.Debug, "Parsed {0} as valid python", expression.Template); pythonExpressions.Add(expression); break; } } } } return(pythonExpressions); }
protected override void DoAction() { IPythonEngine engine = GetCurrentCore().PythonEngine; try { foreach (var module in Modules.Split(',').Select(s => s.Trim())) { if (module == "os") { //workaround for os module not included in embedded ironpython this.OsModuleWorkaround(); } else { engine.ImportModule(module); } } } catch (PythonException e) { throw new ActionException(e, this); } }
public PythonEngineController(IPythonEngine pythonEngine) { m_pythonEngine = pythonEngine; Initialize(); }
public void CompileWith(IPythonEngine engine) { this.Compiled = engine.Compile(Code, SourceCodeType.Expression); }