Beispiel #1
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 EvaluateIronPythonScript(
            string code,
            IList bindingNames,
            [ArbitraryDimensionArrayImport] IList bindingValues)
        {
            var engine = Python.CreateEngine();
            var scope  = engine.CreateScope();

            var amt = Math.Min(bindingNames.Count, bindingValues.Count);

            for (int i = 0; i < amt; i++)
            {
                scope.SetVariable((string)bindingNames[i], InputMarshaler.Marshal(bindingValues[i]));
            }

            try
            {
                OnEvaluationBegin(engine, scope, code, bindingValues);
                engine.CreateScriptSourceFromString(code).Execute(scope);
            }
            catch (Exception e)
            {
                OnEvaluationEnd(false, engine, scope, code, bindingValues);
                throw e;
            }

            OnEvaluationEnd(true, engine, scope, code, bindingValues);

            var result = scope.ContainsVariable("OUT") ? scope.GetVariable("OUT") : null;

            return(OutputMarshaler.Marshal(result));
        }
Beispiel #2
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);
        }
        /// <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 EvaluateIronPythonScript(
            string code,
            IList bindingNames,
            [ArbitraryDimensionArrayImport] IList bindingValues)
        {
            if (code != prev_code)
            {
                ScriptSource script = Python.CreateEngine().CreateScriptSourceFromString(code);
                script.Compile();
                prev_script = script;
                prev_code   = code;
            }

            ScriptEngine engine = prev_script.Engine;
            ScriptScope  scope  = engine.CreateScope();

            int amt = Math.Min(bindingNames.Count, bindingValues.Count);

            for (int i = 0; i < amt; i++)
            {
                scope.SetVariable((string)bindingNames[i], InputMarshaler.Marshal(bindingValues[i]));
            }

            try
            {
                OnEvaluationBegin(engine, scope, code, bindingValues);
                prev_script.Execute(scope);
            }
            catch (Exception e)
            {
                OnEvaluationEnd(false, engine, scope, code, bindingValues);
                var    eo    = engine.GetService <ExceptionOperations>();
                string error = eo.FormatException(e);
                throw new Exception(error);
            }

            OnEvaluationEnd(true, engine, scope, code, bindingValues);

            var result = scope.ContainsVariable("OUT") ? scope.GetVariable("OUT") : null;

            return(OutputMarshaler.Marshal(result));
        }
Beispiel #4
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)
        {
            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);
            }
        }
Beispiel #5
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 EvaluateIronPythonScript(
            string code,
            IList bindingNames,
            [ArbitraryDimensionArrayImport] IList bindingValues)
        {
            // TODO - it would be nice if users could modify a preference
            // setting enabling the ability to load additional paths

            // Container for paths that will be imported in the PythonEngine
            List <string> paths = new List <string>();

            // Attempt to get the Standard Python Library
            string stdLib = PythonStandardLibPath();

            if (code != prev_code)
            {
                ScriptEngine PythonEngine = Python.CreateEngine();
                if (!string.IsNullOrEmpty(stdLib))
                {
                    code  = "import sys" + System.Environment.NewLine + code;
                    paths = PythonEngine.GetSearchPaths().ToList();
                    paths.Add(stdLib);
                }

                // If any paths were successfully retrieved, append them
                if (paths.Count > 0)
                {
                    PythonEngine.SetSearchPaths(paths);
                }

                ScriptSource script = PythonEngine.CreateScriptSourceFromString(code);
                script.Compile();
                prev_script = script;
                prev_code   = code;
            }

            ScriptEngine engine = prev_script.Engine;
            ScriptScope  scope  = engine.CreateScope();

            ProcessAdditionalBindings(scope, bindingNames, bindingValues);

            int amt = Math.Min(bindingNames.Count, bindingValues.Count);

            for (int i = 0; i < amt; i++)
            {
                scope.SetVariable((string)bindingNames[i], InputMarshaler.Marshal(bindingValues[i]));
            }

            try
            {
                OnEvaluationBegin(engine, scope, code, bindingValues);
                prev_script.Execute(scope);
            }
            catch (Exception e)
            {
                OnEvaluationEnd(false, engine, scope, code, bindingValues);
                var    eo    = engine.GetService <ExceptionOperations>();
                string error = eo.FormatException(e);
                throw new Exception(error);
            }

            OnEvaluationEnd(true, engine, scope, code, bindingValues);

            var result = scope.ContainsVariable("OUT") ? scope.GetVariable("OUT") : null;

            return(OutputMarshaler.Marshal(result));
        }