/// <summary> /// Load a module into a scope. /// </summary> /// <param name="name">Name to be assigned to the module</param> /// <param name="fileName">Name of the code file.</param> /// <param name="globals">Globals to be set before execution of the script.</param> /// <returns>PyScope with code loaded.</returns> private PyScope LoadModule(string name, string fileName, Dictionary <string, object> globals) { PyScope scope = null; using (Py.GIL()) { // Create a new scope scope = Py.CreateScope(name); // Assign any globals. if (globals != null) { foreach (string gname in globals.Keys) { scope.Set(gname, globals[gname]); } } // Load python code, compile, then execute it in the scope. string scriptText = File.ReadAllText(fileName); PyObject code = PythonEngine.Compile(scriptText, fileName); dynamic r = scope.Execute(code); } return(scope); }
public void TestCompileExpression() { using (Py.GIL()) { ps.Set("bb", 100); //declare a global variable ps.Set("cc", 10); //declare a local variable PyObject script = PythonEngine.Compile("bb + cc + 3", "", RunFlagType.Eval); var result = ps.Execute <int>(script); Assert.AreEqual(113, result); } }
public void TestCompileStatements() { using (Py.GIL()) { ps.Set("bb", 100); //declare a global variable ps.Set("cc", 10); //declare a local variable PyObject script = PythonEngine.Compile("aa = bb + cc + 3", "", RunFlagType.File); ps.Execute(script); var result = ps.Get <int>("aa"); Assert.AreEqual(113, result); } }
public static void ExecFile(this PyScope scope, string path) { if (!File.Exists(path)) { throw new FileNotFoundException(path); } var txt = File.ReadAllText(path, Encoding.UTF8); using (Py.GIL()) { var script = PythonEngine.Compile(txt, new FileInfo(path).FullName, RunFlagType.File); scope.Execute(script)?.Dispose(); } }
public static RunTextWriterDelegate CompileScript(string code, TextGeneratorLanguage language) { switch (language) { case TextGeneratorLanguage.Python: return(delegate(Stream fw, IDictionary <string, object> extnames, IDictionary <string, object> outnames) { PythonEngine engine = new PythonEngine(); ScriptingEnv.InitializeEngine(engine); engine.SetStandardOutput(fw); CompiledCode compiled = engine.Compile(code); //if (node != null) node.GetScriptingNS(engine.DefaultModule.Globals); if (extnames != null) { foreach (string key in extnames.Keys) { engine.DefaultModule.Globals[key] = extnames[key]; } } compiled.Execute(); if (outnames != null) { foreach (string key in engine.DefaultModule.Globals.Keys) { outnames[key] = engine.DefaultModule.Globals[key]; } } }); case TextGeneratorLanguage.Template: return(delegate(Stream fw, IDictionary <string, object> extnames, IDictionary <string, object> outnames) { PythonEngine engine = new PythonEngine(); engine.SetStandardOutput(fw); ScriptingEnv.InitializeEngine(engine); //if (node != null) node.GetScriptingNS(engine.DefaultModule.Globals); if (extnames != null) { foreach (string key in extnames.Keys) { engine.DefaultModule.Globals[key] = extnames[key]; } } Template tpl = new Template(code, engine); StreamWriter sw = new StreamWriter(fw); TemplateEnviroment env = new TemplateEnviroment(sw); tpl.Run(env); }); } throw new Exception("DAE-00258 internal error"); }
/// <summary> /// Compile the code in the __main__ module of the interpreter. /// </summary> /// <param name="code">the code to compile</param> /// <returns>the object that was compiled</returns> public static object CompileScript(string code) { object rv; if (code == null) { return(null); } try { rv = interpreter.Compile(code); } catch (Exception ex) { LogUtil.ExceptionLog.InfoFormat("Failed to compile scripting code: \n{0}", code); LogUtil.ExceptionLog.Warn(ex.ToString()); return(null); } return(rv); }
/// <summary> /// send the command to python /// </summary> private void SendCommand() { string rawCommand = this.TB.Text.Remove(0, this.TextBasePosition).Trim(); if (rawCommand.EndsWith(":")) { // Not implement this.TB.Text += Environment.NewLine; this.TB.Text += this.Prompt; this.Focus(); this.TB.Select(this.TB.Text.Length, 0); //move cursor to the end return; } if (!string.IsNullOrEmpty(rawCommand)) { this.TB.Text += Environment.NewLine; using (Py.GIL()) { try { PyObject script = PythonEngine.Compile(rawCommand, "", RunFlagType.Single); var res = this.PyScope.Execute(script); if (res != null) { this.WriteLine(res.ToString()); } } catch (Exception ex) { this.WriteLine(ex.Message); } } } this.TB.Text += this.Prompt; this.TB.SelectionStart = this.TB.Text.Length; this.TB.ScrollToEnd(); this.HistoryCommand.Append(rawCommand); this.UpdateTextBasePosition(); }
public void TestCreate() { using var scope = Py.CreateScope(); Assert.IsFalse(PyModule.SysModules.HasKey("testmod")); PyModule testmod = new PyModule("testmod"); testmod.SetAttr("testattr1", "True".ToPython()); PyModule.SysModules.SetItem("testmod", testmod); using PyObject code = PythonEngine.Compile( "import testmod\n" + "x = testmod.testattr1" ); scope.Execute(code); Assert.IsTrue(scope.TryGet("x", out dynamic x)); Assert.AreEqual("True", x.ToString()); }
public string ExecuteCommand(string command) { string result; try { using (Py.GIL()) { var pyCompile = PythonEngine.Compile(command); m_scope.Value.Execute(pyCompile); result = m_logger.ReadStream(); m_logger.flush(); } } catch (Exception ex) { result = $"Trace: \n{ex.StackTrace} " + "\n" + $"Message: \n {ex.Message}" + "\n"; } return(result); }
protected virtual void UpdateSignature() { if (this.Graph == null) // file path resolving only possible when module is attached to graph { return; } logger.LogInformation("UpdateSignature"); lock (gate) { PySignature signature = null; // when there is no script available var src = this.GetScript(); if (string.IsNullOrEmpty(src)) { // there are no arguments signature = new PySignature(); this.Script = null; SetParserError(null); } else { mainThread.RunSync(() => { using (PyScope ps = Py.CreateScope()) { PyObject script = PythonEngine.Compile(src, filename ?? "", mode); ps.Execute(script); signature = PySignature.GetSignature(ps, this.FunctionName); this.Script = script; } }); this.SetParserError(null); } try { this.signature = signature; // remove all argument pins that no longer exist var unusedPins = argumentPins.Where(pin => !signature.HasArgument(pin.Id)).ToArray(); foreach (var unusedPin in unusedPins) { unusedPin.DisconnectAll(); argumentPins.Remove(unusedPin); logger.LogInformation($"Removing input pin: {unusedPin.Id}"); inputs.Remove(unusedPin); } foreach (var arg in signature.Arguments) { var existingPin = argumentPins.FirstOrDefault(x => x.Id == arg.Name); if (existingPin == null) { var newPin = this.AddInputPin(arg.Name, PinDataTypeFactory.FromType(arg.Type), PropertyMode.Allow); argumentPins.Add(newPin); } else { // check type if (existingPin.DataType.UnderlyingType != arg.Type) { existingPin.ChangeType(PinDataTypeFactory.FromType(arg.Type)); } } } // get all pin ids which are not member of this dynamic pin collection var nonDynamicPinIds = this.inputs.Where(x => !argumentPins.Contains(x)).Select(x => x.ObjectId); // reorder module input pins var orderedArgumentPinObjectIds = signature.Arguments.Select(x => argumentPins.First(y => y.Id == x.Name).ObjectId); var newOrder = nonDynamicPinIds.Concat(orderedArgumentPinObjectIds).ToArray(); this.inputs.Reorder(newOrder); // analyse return type of script Type[] returnTypes; if (signature.ReturnType == null) { returnTypes = new Type[0]; } else if (TypeHelpers.IsTuple(signature.ReturnType)) { returnTypes = TypeHelpers.GetTupleTypes(signature.ReturnType); } else { returnTypes = new Type[] { signature.ReturnType }; } // remove pins that are not needed anymore while (resultPins.Count > returnTypes.Length) { var last = resultPins[resultPins.Count - 1]; logger.LogInformation($"Removing output pin: {last.Id}"); last.DisconnectAll(); outputs.Remove(last); resultPins.RemoveAt(resultPins.Count - 1); } for (int i = 0; i < returnTypes.Length; i++) { if (i < resultPins.Count) { var existingPin = resultPins[i]; if (existingPin.DataType.UnderlyingType != returnTypes[i]) { existingPin.ChangeType(PinDataTypeFactory.FromType(returnTypes[i])); } } else { var newPin = this.AddOutputPin($"output{i}", PinDataTypeFactory.FromType(returnTypes[i])); resultPins.Add(newPin); } } } catch (Exception e) { throw; } } }