private void PyScript_StartCompilingEventHandler(object sender, EventArgs e)
        {
            var code = pyScript.CurrentFile.ScriptContent;

            if (string.IsNullOrEmpty(code))
            {
                return;
            }
            try
            {
                using (Py.GIL())
                {
                    using (var scope = Py.CreateScope())
                    {
                        scope.Exec(code);

                        dynamic analyzeClass = scope.Get <dynamic>("Analyze");
                        dynamic analyze      = analyzeClass();
                        analyze.run();
                        analyze.show_graph();
                    }
                }
            }
            catch (Exception ex)
            {
                pyScript.SetError(ex.ToString());
            }
        }
        public string Run(string code, string template, Dictionary <string, string> variables)
        {
            using (Py.GIL())
            {
                using (var scope = Py.CreateScope())
                {
                    scope.Set("result", "");
                    scope.Set("template", template);

                    using (var pyVariables = new PyDict())
                    {
                        foreach (var variable in variables)
                        {
                            pyVariables[variable.Key] = variable.Value.ToPython();
                        }

                        scope.Set("variables", pyVariables);

                        scope.Set("get_clipboard_text", (Func <string>)(() => _clipboardService.GetText()));
                        scope.Set("set_clipboard_text", (Action <string>)((text) => _clipboardService.SetText(text)));

                        scope.Exec(code);

                        return(scope.Get <string>("result"));
                    }
                }
            }
        }
Example #3
0
        public void Run()
        {
            using (PyScope scope = Py.CreateScope())
            {
                dynamic np = Py.Import("numpy");
                Console.WriteLine(np.cos(np.pi * 2));

                dynamic sin = np.sin;
                Console.WriteLine(sin(5));

                Double c = np.cos(5) + sin(5);
                Console.WriteLine(c);

                dynamic a = np.array(new List <float> {
                    1, 2, 3
                });
                Console.WriteLine(a.dtype);

                dynamic b = np.array(new List <float> {
                    6, 5, 4
                }, dtype: np.int32);
                Console.WriteLine(b.dtype);

                Console.WriteLine(a * b);
            }
        }
        public void TestDict()
        {
            using (Py.GIL())
            {
                //create a instance of PyConverter
                var converter = NewMyDictConverter();

                var scope = Py.CreateScope();
                scope.Exec(
                    "a={'0': 1, '1': [1, \"2\"]}"
                    );
                dynamic a = scope.Get("a");

                var b = converter.ToClr(a);        //b is a List of CLR objects

                var    c  = converter.ToPython(b); //
                object c0 = c["0"];
                object c1 = c["1"];

                var    d  = converter.ToClr(c);
                object d0 = d["0"];
                object d1 = d["1"];

                scope.Dispose();
            }
        }
Example #5
0
        /// <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));
                    }
                }
            }
        }
Example #6
0
        static async Task Main(string[] args)
        {
            await Installer.SetupPython();

            using (Py.GIL())
            {
                string a = "def funcname(a):"
                           + Environment.NewLine
                           + "    i = 12"
                           + Environment.NewLine
                           + "    a = i+25"
                           + Environment.NewLine
                           + "    print(i)"
                           + Environment.NewLine
                           + "    print(a)"
                           + Environment.NewLine
                           + "    return a";
                PyScope  pyScope  = Py.CreateScope();
                PyObject pyObject = PythonEngine.ModuleFromString("a", a);
                pyScope.ImportAll(pyObject);
                PyObject eval = pyScope.Eval("funcname(15)");
                Console.Out.WriteLine("eval = {0}", eval);
                eval.GetPythonType().WriteLine();
                var @as = eval.As <int>();
                Console.Out.WriteLine("@as = {0}", @as);
            }

            Console.ReadKey();
        }
Example #7
0
        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());
                }
        }
Example #8
0
        /// <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);
        }
Example #9
0
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            // オブジェクトはスコープ内で変換
            if (value.GetType().IsClass)
            {
                using (var scope = Py.CreateScope())
                {
                    // convert the binder object to a PyObject
                    var pyPerson = binder.ToPython();

                    // create a Python variable "person"
                    scope.Set("person", pyPerson);

                    // the person object may now be used in Python
                    var code = "fullName = person.FirstName + ' ' + person.LastName";
                    scope.Exec(code);
                }
            }
            // プリミティブはそのまま戻す
            else
            {
                binder.Name.ToPython().SetAttr(binder.Name, value.ToPython());
            }

            return(true);
        }
Example #10
0
        public void TestPythonException_PyErr_NormalizeException()
        {
            using (var scope = Py.CreateScope())
            {
                scope.Exec(@"
class TestException(NameError):
    def __init__(self, val):
        super().__init__(val)
        x = int(val)");
                Assert.IsTrue(scope.TryGet("TestException", out PyObject type));

                PyObject str     = "dummy string".ToPython();
                var      typePtr = new NewReference(type.Reference);
                var      strPtr  = new NewReference(str.Reference);
                var      tbPtr   = new NewReference(Runtime.Runtime.None.Reference);
                Runtime.Runtime.PyErr_NormalizeException(ref typePtr, ref strPtr, ref tbPtr);

                using var typeObj = typePtr.MoveToPyObject();
                using var strObj  = strPtr.MoveToPyObject();
                using var tbObj   = tbPtr.MoveToPyObject();
                // the type returned from PyErr_NormalizeException should not be the same type since a new
                // exception was raised by initializing the exception
                Assert.IsFalse(PythonReferenceComparer.Instance.Equals(type, typeObj));
                // the message should now be the string from the throw exception during normalization
                Assert.AreEqual("invalid literal for int() with base 10: 'dummy string'", strObj.ToString());
            }
        }
Example #11
0
 public void SetUp()
 {
     using (Py.GIL())
     {
         ps = Py.CreateScope("test");
     }
 }
Example #12
0
        static void Main(string[] args)
        {
            string preamble =
                "import clr\n" +
                "clr.AddReference('MyModule')\n" +
                "from MyModule import MyClass\n" +
                "import sys\n" +
                "print(sys.version)";

            string callWithFloatArgs = "result = MyClass.Add(1.0, 2.0)";
            string callWithIntArgs   = "result = MyClass.Add(1, 2)";
            string callWithMixedArgs = "result = MyClass.Add(1.0, 2)";

            PythonEngine.Initialize();
            using (Py.GIL())
            {
                using (PyScope scope = Py.CreateScope())
                {
                    scope.Exec(preamble);

                    scope.Exec(callWithFloatArgs);
                    System.Console.WriteLine(scope.Get("result")); // prints "3.0"

                    scope.Exec(callWithIntArgs);
                    System.Console.WriteLine(scope.Get("result")); // prints "3"

                    scope.Exec(callWithMixedArgs);                 // Python.Runtime.PythonException: 'TypeError : No method matches given arguments for Add'
                    System.Console.WriteLine(scope.Get("result"));
                }
            }
        }
Example #13
0
        /// <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);
            }
        }
Example #14
0
        /// <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);
                    }
                }
            }
        }
Example #15
0
        void Analyze(string path)
        {
            var data = File.ReadAllText(path);
            var name = Path.GetFileNameWithoutExtension(path);

            using (PyScope scope = Py.CreateScope())
            {
                scope.Import("sys");
                scope.Import("os");
                var dir = Path.GetDirectoryName(path);
                var com = $"sys.path.append({dir})";
                scope.Exec("p = os.getcwd()");
                var p = scope.Get("p");
                //scope.Exec(com);
                scope.Exec(data);
                var v       = scope.Get(name);
                var mapping = v.GetAttr("mapping");
                var items   = mapping.GetAttr("keys");

                foreach (var item in mapping)
                {
                    var command = item.ToPython();
                    var target  = mapping.GetItem(command);
                    commands[command.ToString()] = target;
                }
            }
        }
        public void TestObject()
        {
            using (Py.GIL())
            {
                var scope = Py.CreateScope();
                scope.Exec(
                    "class TestObject(object): \n" +
                    "    def __init__(self): \n" +
                    "        self.id = 0 \n" +
                    "        self.Name = ''\n" +
                    "        self.addr = ''\n" +
                    "a = TestObject()\n" +
                    "a.id = 1 \n" +
                    "a.Name = 'create_in_python' \n" +
                    "a.addr = 'python' \n"
                    );
                var converter = NewMyDictConverter();
                converter.AddObjectType <ObjectType>(scope.Get("TestObject"));

                var a = scope.Get("a");
                var b = converter.ToClr(a);         //b is a List of CLR objects

                dynamic c  = converter.ToPython(b); //
                object  c0 = c.id;
                object  c1 = c.Name;

                var d = converter.ToClr(c);
                scope.Dispose();
            }
        }
Example #17
0
        public REPLTextBox()
        {
            this.TB = new TextBox()
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment   = VerticalAlignment.Stretch
            };
            this.Content = this.TB;

            this.Prompt           = ">>> ";
            this.HistoryCommand   = new StringBuilder();
            this.TB.Text          = "";
            this.TextBasePosition = 0;
            using (Py.GIL())
            {
                this.WelcomeMsg = $"Python{PythonEngine.Version}\n";
            }
            this.Clear();
            this.TB.KeyDown          += new KeyEventHandler(this._OnKeyDown);
            this.TB.PreviewKeyDown   += new KeyEventHandler(this._OnPreviewKeyDown);
            this.TB.PreviewTextInput += new TextCompositionEventHandler(this._OnPreviewTextInput);
            this.PreviewKeyUp        += new KeyEventHandler(this._OnPreviewKeyUp);
            this.TB.KeyUp            += new KeyEventHandler(this._OnKeyUp);

            using (Py.GIL())
            {
                PyScope = Py.CreateScope();
            }
            Console.SetOut(new TBTextWriter(this));
        }
Example #18
0
        public void TestPythonException_PyErr_NormalizeException()
        {
            using (var scope = Py.CreateScope())
            {
                scope.Exec(@"
class TestException(NameError):
    def __init__(self, val):
        super().__init__(val)
        x = int(val)");
                Assert.IsTrue(scope.TryGet("TestException", out PyObject type));

                PyObject str     = "dummy string".ToPython();
                IntPtr   typePtr = type.Handle;
                IntPtr   strPtr  = str.Handle;
                IntPtr   tbPtr   = Runtime.Runtime.None.Handle;
                Runtime.Runtime.XIncref(typePtr);
                Runtime.Runtime.XIncref(strPtr);
                Runtime.Runtime.XIncref(tbPtr);
                Runtime.Runtime.PyErr_NormalizeException(ref typePtr, ref strPtr, ref tbPtr);

                using (PyObject typeObj = new PyObject(typePtr), strObj = new PyObject(strPtr), tbObj = new PyObject(tbPtr))
                {
                    // the type returned from PyErr_NormalizeException should not be the same type since a new
                    // exception was raised by initializing the exception
                    Assert.AreNotEqual(type.Handle, typePtr);
                    // the message should now be the string from the throw exception during normalization
                    Assert.AreEqual("invalid literal for int() with base 10: 'dummy string'", strObj.ToString());
                }
            }
        }
Example #19
0
 public void Run(string cmd)
 {
     using (PyScope scope = Py.CreateScope())
     {
         scope.Exec(cmd);
     }
 }
Example #20
0
 public YTDLPyBridge(YouTubeDL youtubeDL)
 {
     ytdl = youtubeDL;
     using (Py.GIL())
     {
         PyScope = Py.CreateScope();
     }
 }
Example #21
0
        /// <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);
        }
Example #22
0
 static ToStrTool()
 {
     using (Py.GIL())
     {
         var scope = Py.CreateScope();
         scope.Set("instance", new ToStrToolTest());
         HasEncodingProblem = scope.Eval("len(str(instance)) != 10").IsTrue();
     };
 }
Example #23
0
 public static void ResetTempScope()
 {
     if (ScriptScopes.ContainsKey("Temp"))
     {
         ScriptScopes["Temp"].Dispose();
         ScriptScopes.Remove("Temp");
     }
     ScriptScopes.Add("Temp", Py.CreateScope());
 }
Example #24
0
 public CPythonRuntime()
 {
     PythonEngine.PythonPath += ";" + Path.GetDirectoryName(typeof(CPythonRuntime).Assembly.Location);
     Log.WriteLine("PythonPath = {0}", PythonEngine.PythonPath);
     m_GIL   = Py.GIL();
     m_scope = Py.CreateScope();
     //TODO make sure the GraphEngine wheel is installed
     m_scope.Exec(@"import GraphEngine");
 }
Example #25
0
        public void ExceptionDecodedNoInstance()
        {
            PyObjectConversions.RegisterDecoder(new InstancelessExceptionDecoder());
            using var scope = Py.CreateScope();
            var error = Assert.Throws <ValueErrorWrapper>(() => PythonEngine.Exec(
                                                              $"[].__iter__().__next__()"));

            Assert.AreEqual(TestExceptionMessage, error.Message);
        }
Example #26
0
        public void ExceptionDecoded()
        {
            PyObjectConversions.RegisterDecoder(new ValueErrorCodec());
            using var scope = Py.CreateScope();
            var error = Assert.Throws <ValueErrorWrapper>(()
                                                          => PythonEngine.Exec($"raise ValueError('{TestExceptionMessage}')"));

            Assert.AreEqual(TestExceptionMessage, error.Message);
        }
Example #27
0
 public void Run(OpenCvSharp.Mat src, string cmd)
 {
     using (PyScope scope = Py.CreateScope())
     {
         PyObject pySrc = src.ToPython();
         scope.Set("src", pySrc);
         scope.Exec(cmd);
     }
 }
Example #28
0
        public void BaseClearIsCalled()
        {
            using var scope = Py.CreateScope();
            scope.Set("exn", new Exception("42"));
            var msg = scope.Eval("exn.args[0]");

            Assert.AreEqual(2, msg.Refcount);
            scope.Set("exn", null);
            Assert.AreEqual(1, msg.Refcount);
        }
Example #29
0
 private static PyObject EncodeTimeSpan(TimeSpan x)
 {
     using (var scope = Py.CreateScope())
     {
         scope.Import("datetime");
         var microseconds = x.Ticks / 10L % 1000000L;
         scope.Exec($"a = datetime.timedelta(days={x.Days}, hours={x.Hours}, minutes={x.Minutes}, seconds={x.Seconds}, microseconds={microseconds}");
         return(scope.Get("a"));
     }
 }
Example #30
0
        public void CallExtraBaseMethod()
        {
            var instance = new Inherited();

            using var scope = Py.CreateScope();
            scope.Set(nameof(instance), instance);
            int actual = instance.ToPython().InvokeMethod("callVirt").As <int>();

            Assert.AreEqual(expected: Inherited.OverridenVirtValue, actual);
        }