public void TestImportScopeFunction() { using (Py.GIL()) { ps.Set("bb", 100); ps.Set("cc", 10); ps.Exec( "def func1():\n" + " return cc + bb\n"); using (PyScope scope = ps.NewScope()) { //'func1' is imported from the origion scope scope.Exec( "def func2():\n" + " return func1() - cc - bb\n"); dynamic func2 = scope.Get("func2"); var result1 = func2().As <int>(); Assert.AreEqual(0, result1); scope.Set("cc", 20);//it has no effect on the globals of 'func1' var result2 = func2().As <int>(); Assert.AreEqual(-10, result2); scope.Set("cc", 10); //rollback ps.Set("cc", 20); var result3 = func2().As <int>(); Assert.AreEqual(10, result3); ps.Set("cc", 10); //rollback } } }
/// <summary> /// Runs a Python script in the Unity process. /// </summary> /// <param name="pythonFileToExecute">The script to execute.</param> /// <param name="scopeName">Value to write to Python special variable `__name__`</param> public static void RunFile(string pythonFileToExecute, string scopeName = null) { EnsureInitialized(); if (null == pythonFileToExecute) { throw new System.ArgumentNullException("pythonFileToExecute", "Invalid (null) file path"); } // Ensure we are getting the full path. pythonFileToExecute = Path.GetFullPath(pythonFileToExecute); // Forward slashes please pythonFileToExecute = pythonFileToExecute.Replace("\\", "/"); if (!File.Exists(pythonFileToExecute)) { throw new System.IO.FileNotFoundException("No Python file found at " + pythonFileToExecute, pythonFileToExecute); } using (Py.GIL()) { if (string.IsNullOrEmpty(scopeName)) { PythonEngine.Exec(string.Format("exec(open('{0}').read())", pythonFileToExecute)); } else { using (PyScope scope = Py.CreateScope()) { scope.Set("__name__", scopeName); scope.Set("__file__", pythonFileToExecute); scope.Exec(string.Format("exec(open('{0}').read())", pythonFileToExecute)); } } } }
/// <summary> /// Migrates Python 2 code to Python 3 using Pythons 2to3 library. /// </summary> /// <param name="code">Python 2 code that needs to be migrated</param> /// <returns></returns> internal static string MigrateCode(string code) { InstallPython(); if (!PythonEngine.IsInitialized) { PythonEngine.Initialize(); PythonEngine.BeginAllowThreads(); } IntPtr gs = PythonEngine.AcquireLock(); try { using (Py.GIL()) { string output; var asm = Assembly.GetExecutingAssembly(); using (PyScope scope = Py.CreateScope()) { scope.Set(INPUT_NAME, code.ToPython()); var path = Path.GetDirectoryName(asm.Location); scope.Set(PATH_NAME, path.ToPython()); scope.Exec(Get2To3MigrationScript(asm)); output = scope.Contains(RETURN_NAME) ? scope.Get(RETURN_NAME).ToString() : string.Empty; } // If the code contains tabs, normalize the whitespaces. This is a Python 3 requirement // that's not addressed by 2to3. if (output.Contains("\t")) { using (PyScope scope = Py.CreateScope()) { scope.Set(INPUT_NAME, output.ToPython()); scope.Exec(GetReindentationScript(asm)); output = scope.Contains(RETURN_NAME) ? scope.Get(RETURN_NAME).ToString() : string.Empty; } } return(output); } } finally { PythonEngine.ReleaseLock(gs); } }
public static void LoadScript(string name, string file) { PyScope scriptScope = Py.CreateScope(); scriptScope.Exec(File.ReadAllText(Path.Combine("PyScripts", file))); if (ScriptScopes.ContainsKey(name)) { ScriptScopes[name].Dispose(); ScriptScopes.Remove(name); } ScriptScopes.Add(name, scriptScope); scriptScope.Set("debuglog", (Action <string>)Debug.Log); scriptScope.Set("debugmsgbox", (Action <string>)Debug.MsgBox); }
/// <summary> /// Processes additional bindings that are not actual inputs. /// Currently, only the node name is received in this way. /// </summary> /// <param name="scope">Python scope where execution will occur</param> /// <param name="bindingNames">List of binding names received for evaluation</param> /// <param name="bindingValues">List of binding values received for evaluation</param> private static void ProcessAdditionalBindings(PyScope scope, IList bindingNames, IList bindingValues) { const string NodeNameInput = "Name"; string nodeName; if (bindingNames.Count == 0 || !bindingNames[0].Equals(NodeNameInput)) { // Defensive code to fallback in case the additional binding is not there, like // when the evaluator is called directly in unit tests. nodeName = "USER"; } else { bindingNames.RemoveAt(0); nodeName = (string)bindingValues[0]; bindingValues.RemoveAt(0); } // Session is null when running unit tests. if (ExecutionEvents.ActiveSession != null) { dynamic logger = ExecutionEvents.ActiveSession.GetParameterValue(ParameterKeys.Logger); Action <string> logFunction = msg => logger.Log($"{nodeName}: {msg}", LogLevel.ConsoleOnly); scope.Set(DynamoPrintFuncName, logFunction.ToPython()); scope.Exec(RedirectPrint()); } }
public void RunFunction(string sFuncName, params string[] args) { using (Py.GIL()) using (PyScope scope = Py.CreateScope()) { Scope = scope; foreach (var kvp in Locals) { var pyName = kvp.Key; PyObject pyObj = kvp.Value.ToPython(); Scope.Set(pyName, pyObj); } Scope.Exec(Script); var functionBuilder = new StringBuilder(); functionBuilder.Append(sFuncName); functionBuilder.Append("("); foreach (var arg in args) { functionBuilder.Append(arg); } functionBuilder.Append(")"); Scope.Exec(functionBuilder.ToString()); } }
/// <summary> /// Migrates Python 2 code to Python 3 using Pythons 2to3 library. /// </summary> /// <param name="code">Python 2 code that needs to be migrated</param> /// <returns></returns> internal static string MigrateCode(string code) { Installer.SetupPython().Wait(); if (!PythonEngine.IsInitialized) { PythonEngine.Initialize(); PythonEngine.BeginAllowThreads(); } IntPtr gs = PythonEngine.AcquireLock(); try { using (Py.GIL()) { using (PyScope scope = Py.CreateScope()) { scope.Set(INPUT_NAME, code.ToPython()); scope.Exec(GetPythonMigrationScript()); var result = scope.Contains(RETURN_NAME) ? scope.Get(RETURN_NAME) : null; return(result.ToString()); } } } finally { PythonEngine.ReleaseLock(gs); } }
/// <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); }
/// <summary> /// Runs Python code in the Unity process. /// </summary> /// <param name="pythonCodeToExecute">The code to execute.</param> /// <param name="scopeName">Value to write to Python special variable `__name__`</param> public static void RunString(string pythonCodeToExecute, string scopeName = null) { if (string.IsNullOrEmpty(pythonCodeToExecute)) { return; } EnsureInitialized(); using (Py.GIL()) { // Clean up the string. dynamic inspect = PythonEngine.ImportModule("inspect"); string code = inspect.cleandoc(pythonCodeToExecute); if (string.IsNullOrEmpty(scopeName)) { PythonEngine.Exec(code); } else { using (PyScope scope = Py.CreateScope()) { scope.Set("__name__", scopeName); scope.Exec(code); } } } }
private static void Write(int writes, PyScope scope) { for (int i = 0; i < writes; i++) { // scope.Exec($"a = {i}"); scope.Set("a", i); } }
/// <summary> /// Executes a Python script with custom variable names. Script may be a string /// read from a file, for example. Pass a list of names (matching the variable /// names in the script) to bindingNames and pass a corresponding list of values /// to bindingValues. /// </summary> /// <param name="code">Python script as a string.</param> /// <param name="bindingNames">Names of values referenced in Python script.</param> /// <param name="bindingValues">Values referenced in Python script.</param> public static object EvaluatePythonScript( string code, IList bindingNames, [ArbitraryDimensionArrayImport] IList bindingValues) { if (code != prev_code) { Python.Included.Installer.SetupPython().Wait(); if (!PythonEngine.IsInitialized) { PythonEngine.Initialize(); PythonEngine.BeginAllowThreads(); } IntPtr gs = PythonEngine.AcquireLock(); try { using (Py.GIL()) { using (PyScope scope = Py.CreateScope()) { int amt = Math.Min(bindingNames.Count, bindingValues.Count); for (int i = 0; i < amt; i++) { scope.Set((string)bindingNames[i], InputMarshaler.Marshal(bindingValues[i]).ToPython()); } try { OnEvaluationBegin(scope, code, bindingValues); scope.Exec(code); OnEvaluationEnd(false, scope, code, bindingValues); var result = scope.Contains("OUT") ? scope.Get("OUT") : null; return(OutputMarshaler.Marshal(result)); } catch (Exception e) { OnEvaluationEnd(false, scope, code, bindingValues); throw e; } } } } catch (PythonException pe) { throw pe; } finally { PythonEngine.ReleaseLock(gs); } } return(null); }
public void Run(OpenCvSharp.Mat src, string cmd) { using (PyScope scope = Py.CreateScope()) { PyObject pySrc = src.ToPython(); scope.Set("src", pySrc); scope.Exec(cmd); } }
public void PostRequestChord(string input) { try { using (Py.GIL()) { PyList pyTest = new PyList(); Console.WriteLine(input); if (input.Contains("c") == false) { listaNotas.Add(input); } if (input.Contains("c")) { listaNotas.Remove(input.Remove(input.Length - 1)); } using (PyScope scope = Py.CreateScope()) { for (int i = 0; i < listaNotas.Count; i++) { pyTest.Append(new PyString(listaNotas[i])); Console.WriteLine(listaNotas[i]); } scope.Set("test", pyTest); dynamic chord = scope.Get("test"); dynamic pychord = scope.Import("pychord"); dynamic music21 = scope.Import("music21"); dynamic myChord = pychord.analyzer.find_chords_from_notes(chord); if (Convert.ToString(myChord) == "[]") { myChord = music21.chord.Chord(chord); myChord = myChord.pitchedCommonName; } Console.WriteLine(myChord); string value = Convert.ToString(myChord); notaSalida.Text = value; } } } catch { } }
public object Run( [InputPin(Name = "caption", Description = "The caption of this module", PropertyMode = PropertyMode.Always, Editor = WellKnownEditors.SingleLineText)] string caption, [InputPin(Name = "expression", Description = "The Python expression", PropertyMode = PropertyMode.Always, Editor = WellKnownEditors.SingleLineText)] string expression, [InputPin(Name = "useMainThread", Description = "Whether to run the code on the Python main thread", PropertyMode = PropertyMode.Always, Editor = WellKnownEditors.CheckBox, DefaultValue = "false")] bool useMainThread, [InputPin(Name = "input", Description = "These are the inputs for the expression", PropertyMode = PropertyMode.Never)] params object[] inputs ) { object evalBlock() { using (PyScope ps = Py.CreateScope()) { int i = 0; foreach (var inputPin in this.dynamicInputPin.Pins) { if (inputPin.Connections.Any()) { ps.Set(inputPin.Id, PyConvert.ToPyObject(inputs[i])); } i++; } ps.Set(dynamicInputPin.Alias + "s", inputs); PyObject evalResult = ps.Eval(expression); return(PyConvert.ToClrObject(evalResult, typeof(object))); } } if (useMainThread) { return(mainThread.EvalSync(evalBlock)); } else { using (Py.GIL()) { return(evalBlock()); } } }
public void Run() { Person person = new Person("Bob", "Davies"); using (PyScope scope = Py.CreateScope()) { PyObject pyPerson = person.ToPython(); scope.Set("person", pyPerson); string code = "Fullname = person.FirstName + ' ' + person.LastName"; scope.Exec(code); string printit = "print (person.FirstName)"; scope.Exec(printit); } }
/// <summary> /// Called immediately before evaluation starts /// </summary> /// <param name="scope">The scope in which the code is executed</param> /// <param name="code">The code to be evaluated</param> /// <param name="bindingValues">The binding values - these are already added to the scope when called</param> private void OnEvaluationBegin(PyScope scope, string code, IList bindingValues) { // Call deprecated events until they are completely removed. EvaluationBegin?.Invoke(EvaluationState.Begin, scope, code, bindingValues); if (EvaluationStarted != null) { EvaluationStarted(code, bindingValues, (n, v) => { scope.Set(n, InputMarshaler.Marshal(v).ToPython()); }); Analytics.TrackEvent( Dynamo.Logging.Actions.Start, Dynamo.Logging.Categories.PythonOperations, "CPythonEvaluation"); } }
public void Run() { using (Py.GIL()) using (PyScope scope = Py.CreateScope()) { Scope = scope; foreach (var kvp in Locals) { var pyName = kvp.Key; PyObject pyObj = kvp.Value.ToPython(); Scope.Set(pyName, pyObj); } Scope.Exec(Script); } }
public object QueryAsync(string code) { using IServiceScope scope = _serviceProvider.CreateScope(); UsageRecordsRepository repository = scope.ServiceProvider.GetRequiredService <UsageRecordsRepository>(); IEnumerable <UsageRecord> usageRecords = repository.UsageRecords.AsNoTracking(); using Py.GILState gil = Py.GIL(); using PyScope pyScope = Py.CreateScope(); pyScope.Set(nameof(usageRecords), usageRecords.ToPython()); PyObject pyObject = pyScope.Eval(code); if (pyObject.IsIterable()) { return(pyObject.Select(item => item.AsManagedObject(typeof(object)))); } else { object result = pyObject.AsManagedObject(typeof(object)); return(result); } }
public override ValidationResult Validate(object value, CultureInfo cultureInfo) { PyScope scope = PyScriptManager.ScriptScopes["Temp"]; scope.ImportAll("math"); scope.Set("value", value); PyObject result = scope.Eval(Script); string errorMsg; try { errorMsg = result.As <string>(); //Expect true(bool) for valid input, an error message string for invalid input } catch (InvalidCastException) { return(new ValidationResult(true, null)); } return(new ValidationResult(false, errorMsg)); }
public Sudoku Solve(Sudoku s) { using (Py.GIL()) { using (PyScope scope = Py.CreateScope()) { // convert the sudoku object to a PyObject PyObject pySudoku = s.ToPython(); // create a Python variable "sudoku" scope.Set("sudoku", pySudoku); // the sudoku object may now be used in Pythonn string code = "fullName = person.FirstName + ' ' + person.LastName"; scope.Exec(code); s = scope.Get <Sudoku>("sudoku"); } return(s); // PythonEngine.Exec("doStuff()"); } }
private List <byte[]> CreateNSBTXes(SaveForm SF) { List <byte[]> NSBTXes = new List <byte[]>(); using (Py.GIL()) { dynamic TexturePy = Python.Runtime.Py.Import("ndspy.texture"); using (PyScope scope = Py.CreateScope()) { scope.Exec("import ndspy.texture"); for (int j = 0; j < 3; j++) { scope.Exec("nsbtx = ndspy.texture.NSBTX()"); for (int i = 0 + (255 * j); i < 255 + (255 * j); i++) { SF.SetMessage("Encoding Tile " + (i + 1) + " (Format: " + TextureFormats[i] + ")"); Console.WriteLine("Tex " + i); Bitmap TileBitmap = new Bitmap(16, 16); Graphics g = Graphics.FromImage(TileBitmap); g.DrawImage(this.MainPNG, new Rectangle(new Point(0, 0), new Size(16, 16)), Helpers.GetRectangleForTileID(i), GraphicsUnit.Pixel); EncodedImage Enc = null; if (TextureFormats[i] == 7) { Enc = Images.EncodeImage_RGB555(TileBitmap); } else if (TextureFormats[i] == 5) { Enc = Images.Encode_Tex4x4(TileBitmap, 16); } else { PalettedImage p = Images.CreatePalettedImage(TileBitmap, this.TextureFormats[i]); Enc = Images.EncodeImage(p, TextureFormats[i]); } string Name = "Tile " + i.ToString(); dynamic Tex = TexturePy.Texture.fromFlags(0, 0, true, true, false, false, TileBitmap.Width, TileBitmap.Height, this.TextureFormats[i], false, 0, 0x80010040, Enc.Texture, Enc.Texture2); dynamic Pal = TexturePy.Palette.fromColors(0, 0, 0, Enc.Palette); scope.Set("Name", Name.ToPython()); scope.Set("Tex", Tex); scope.Set("Pal", Pal); scope.Exec("nsbtx.textures.append((Name,Tex))"); scope.Exec("nsbtx.palettes.append((Name,Pal))"); } scope.Exec("nsbtxf = nsbtx.save()"); NSBTXes.Add(scope.Get <byte[]>("nsbtxf")); } } } return(NSBTXes); }
public void TestPythonInterop() { var jsonSerializerOptions = new JsonSerializerOptions { WriteIndented = true, Converters = { new JsonStringEnumConverter(), new SimpleHypergridJsonConverter(), new DimensionJsonConverter(), }, }; string csContinuousJsonString = JsonSerializer.Serialize(continuous, jsonSerializerOptions); string csDiscreteJsonString = JsonSerializer.Serialize(discrete, jsonSerializerOptions); string csOrdinalJsonString = JsonSerializer.Serialize(ordinal, jsonSerializerOptions); string csCategoricalJsonString = JsonSerializer.Serialize(categorical, jsonSerializerOptions); string csSimpleHypergridJsonString = JsonSerializer.Serialize(allKindsOfDimensions, jsonSerializerOptions); using (Py.GIL()) { using PyScope pythonScope = Py.CreateScope(); pythonScope.Set("cs_continuous_dimension_json_string", csContinuousJsonString); pythonScope.Set("cs_discrete_dimension_json_string", csDiscreteJsonString); pythonScope.Set("cs_ordinal_dimension_json_string", csOrdinalJsonString); pythonScope.Set("cs_categorical_dimension_json_string", csCategoricalJsonString); pythonScope.Set("cs_simple_hypergrid_json_string", csSimpleHypergridJsonString); pythonScope.Exec(PythonScriptsAndJsons.CreateDimensionsAndSpacesScript); pythonScope.Exec(PythonScriptsAndJsons.DeserializeDimensionsScript); bool successfullyDeserializedDimensions = pythonScope.Get("success").As <bool>(); string exceptionMessage = string.Empty; if (!successfullyDeserializedDimensions) { exceptionMessage = pythonScope.Get("exception_message").As <string>(); } Assert.True(successfullyDeserializedDimensions, exceptionMessage); pythonScope.Exec(PythonScriptsAndJsons.DeserializeSimpleHypergridScript); bool successfullyDeserializedSimpleHypergrid = pythonScope.Get("success").As <bool>(); if (!successfullyDeserializedSimpleHypergrid) { exceptionMessage = pythonScope.Get("exception_message").As <string>(); } Assert.True(successfullyDeserializedSimpleHypergrid, exceptionMessage); string pySimpleHypergridJsonString = pythonScope.Get("py_simple_hypergrid_json_string").As <string>(); SimpleHypergrid simpleHypergridDeserializedFromPython = JsonSerializer.Deserialize <SimpleHypergrid>(pySimpleHypergridJsonString, jsonSerializerOptions); Assert.True(simpleHypergridDeserializedFromPython.Name == "all_kinds_of_dimensions"); Assert.True(simpleHypergridDeserializedFromPython.Dimensions.Count == 4); string reserializedHypergrid = JsonSerializer.Serialize(simpleHypergridDeserializedFromPython, jsonSerializerOptions); pythonScope.Set("cs_reserialized_hypergrid_json_string", reserializedHypergrid); pythonScope.Exec(PythonScriptsAndJsons.ValidateReserializedHypergridScript); bool successfullyValidatedReserializedHypergrid = pythonScope.Get("success").As <bool>(); if (!successfullyValidatedReserializedHypergrid) { exceptionMessage = pythonScope.Get("exception_message").As <string>(); } Assert.True(successfullyValidatedReserializedHypergrid, exceptionMessage); } string currentDirectory = Directory.GetCurrentDirectory(); Console.WriteLine($"Current directory {currentDirectory}"); }
/// <summary> /// Executes a Python script with custom variable names. Script may be a string /// read from a file, for example. Pass a list of names (matching the variable /// names in the script) to bindingNames and pass a corresponding list of values /// to bindingValues. /// </summary> /// <param name="code">Python script as a string.</param> /// <param name="bindingNames">Names of values referenced in Python script.</param> /// <param name="bindingValues">Values referenced in Python script.</param> public static object EvaluatePythonScript( string code, IList bindingNames, [ArbitraryDimensionArrayImport] IList bindingValues) { var evaluationSuccess = true; if (code == null) { return(null); } InstallPython(); if (!PythonEngine.IsInitialized) { PythonEngine.Initialize(); PythonEngine.BeginAllowThreads(); } IntPtr gs = PythonEngine.AcquireLock(); try { using (Py.GIL()) { if (globalScope == null) { globalScope = CreateGlobalScope(); } using (PyScope scope = Py.CreateScope()) { // Reset the 'sys.path' value to the default python paths on node evaluation. var pythonNodeSetupCode = "import sys" + Environment.NewLine + "sys.path = sys.path[0:3]"; scope.Exec(pythonNodeSetupCode); ProcessAdditionalBindings(scope, bindingNames, bindingValues); int amt = Math.Min(bindingNames.Count, bindingValues.Count); for (int i = 0; i < amt; i++) { scope.Set((string)bindingNames[i], InputMarshaler.Marshal(bindingValues[i]).ToPython()); } try { OnEvaluationBegin(scope, code, bindingValues); scope.Exec(code); var result = scope.Contains("OUT") ? scope.Get("OUT") : null; return(OutputMarshaler.Marshal(result)); } catch (Exception e) { evaluationSuccess = false; var traceBack = GetTraceBack(e); if (!string.IsNullOrEmpty(traceBack)) { // Throw a new error including trace back info added to the message throw new InvalidOperationException($"{e.Message} {traceBack}", e); } else { throw e; } } finally { OnEvaluationEnd(evaluationSuccess, scope, code, bindingValues); } } } } finally { PythonEngine.ReleaseLock(gs); } }
protected override async Task <object[]> EvaluateInternal(object[] inputs, CancellationToken cancel) { if (parserError != null) { throw parserError; } var script = this.Script; if (script == null) { return(new object[0]); // no script available } object[] returnValue = null; void evalAction() { // create new python scope using (PyScope ps = Py.CreateScope()) { if (!string.IsNullOrEmpty(filename)) { ps.Set("__file__", filename); } // load script into scope ps.Execute(script); ps.Set("context", this.Runtime.ScriptContext.ToPython()); ps.Set("store", this.Graph.ValueStore.ToPython()); // process module inputs and convert them to python objects int firstArgIndex = inputs.Length - argumentPins.Count; var args = CreateArguments(inputs, firstArgIndex); // call python method string functionName = (string)inputs[FUNCTION_NAME_PIN_INDEX] ?? DEFAULT_FUNCTION_NAME; PyObject fn = ps.Get(functionName); PyObject pyResult = null; try { pyResult = fn.Invoke(args); } catch (PythonException e) { throw new XamlaPythonException(e); } // convert result back to clr object var result = PyConvert.ToClrObject(pyResult, signature.ReturnType); if (result == null) { returnValue = new object[] { null } } ; else if (!result.GetType().IsTuple()) { returnValue = new object[] { result } } ; else { returnValue = TypeHelpers.GetTupleValues(result); } } } int useMainThreadPinIndex = 2; if (this.flowMode != FlowMode.NoFlow) { useMainThreadPinIndex += 1; } bool useMainThread = (bool)inputs[useMainThreadPinIndex]; if (useMainThread) { await mainThread.Enqueue(evalAction, cancel); } else { using (Py.GIL()) { evalAction(); } } if (this.flowMode != FlowMode.NoFlow) { return((new object[] { Flow.Default }.Concat(returnValue)).ToArray()); } else { return(returnValue); } }
public void TestEval() { using (Py.GIL()) { ps.Set("a", 1); var result = ps.Eval <int>("a + 2"); Assert.AreEqual(3, result); } }