Exemple #1
0
        public void InitializeIronPython(Microsoft.Scripting.Hosting.ScriptEngine engine)
        {
            System.Diagnostics.Process          process   = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName               = "cmd.exe";
            startInfo.Arguments              = "/C python -c \"import os, sys; print(os.path.dirname(sys.executable))\"";
            startInfo.CreateNoWindow         = true;
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute        = false;
            process.StartInfo = startInfo;
            process.Start();

            /*dynamic py = engine.ExecuteFile(get_modules);*/
            /*python_exe = process.StandardOutput.ReadToEnd().Replace("\n", "").Replace("\r", "") + @"python.exe";*/
            dir   = process.StandardOutput.ReadToEnd().Replace("\n", "").Replace("\r", "") + @"\Lib\";
            dir2  = dir + @"site-packages\";
            dir3  = dir2 + @"firebase\";
            dir4  = python_scripts;
            paths = engine.GetSearchPaths();
            paths.Add(dir);
            paths.Add(dir2);
            paths.Add(dir3);
            paths.Add(dir4);
            engine.SetSearchPaths(paths);

            Console.WriteLine(dir + "\n" + dir2 + "\n" + dir3 + "\n" + database_access);
        }
 public ImgInterpreter()
 {
     path   = "";
     script = "scripts\\_default.py";
     py     = Python.CreateEngine(); // allows to run ironpython programs
     s      = py.CreateScope();      // you need this to get the variables
 }
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(
                "helloWorldString = 'Hello World!'\n" +
                "print helloWorldString\n" +
                "print externalString"
                );

            Microsoft.Scripting.Hosting.ScriptScope scope = pythonEngine.CreateScope();
            scope.SetVariable("externalString", "How do you do?");

            pythonScript.Execute(scope);

            System.Console.Out.WriteLine();
            System.Console.Out.WriteLine("List of variables in the scope:");
            foreach (string name in scope.GetVariableNames())
            {
                System.Console.Out.Write(name + " ");
            }
            System.Console.Out.WriteLine();

            System.Console.Out.WriteLine();
            System.Console.Out.WriteLine("Variable values:");
            System.Console.Out.WriteLine("helloWorldString: " + scope.GetVariable("helloWorldString"));
            System.Console.Out.WriteLine("externalString: " + scope.GetVariable("externalString"));
        }
Exemple #4
0
        /// <summary>
        /// 用户自定义Python脚本
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string RepairFun_PythonScript(string handler, string source)
        {
            if (source == "")
            {
                return("");
            }

            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(
                $"import textRepairPlugins.{handler} as customHandler\n" +
                "ResultStr = customHandler.process(SourceStr)\n"
                );
            Microsoft.Scripting.Hosting.ScriptScope scope = pythonEngine.CreateScope();
            scope.SetVariable("SourceStr", source);

            try
            {
                pythonScript.Execute(scope);
            }
            catch (Exception e)
            {
                return(e.Message);
            }
            return((string)scope.GetVariable("ResultStr"));
        }
 static void Main(string[] args)
 {
     Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
     // We execute this script from Visual Studio so the program will be executed from bin\Debug or bin\Release
     Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromFile("..\\..\\HelloWorld.py");
     pythonScript.Execute();
 }
Exemple #6
0
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine =
                IronPython.Hosting.Python.CreateEngine();

            // Print the default search paths
            System.Console.Out.WriteLine("Search paths:");
            ICollection <string> searchPaths = pythonEngine.GetSearchPaths();

            foreach (string path in searchPaths)
            {
                System.Console.Out.WriteLine(path);
            }
            System.Console.Out.WriteLine();

            // Now modify the search paths to include the directory
            // where the standard library has been installed
            searchPaths.Add("..\\..\\Lib");
            pythonEngine.SetSearchPaths(searchPaths);

            // Execute the script
            // We execute this script from Visual Studio
            // so the program will executed from bin\Debug or bin\Release
            Microsoft.Scripting.Hosting.ScriptSource pythonScript =
                pythonEngine.CreateScriptSourceFromFile("..\\..\\HelloWorldBase64.py");
            pythonScript.Execute();
        }
Exemple #7
0
        public Script()
        {
            engine = Python.CreateEngine();
            scope = engine.CreateScope();

            scope.SetVariable("cs", MainV2.cs);
            scope.SetVariable("Script", this);

            Console.WriteLine(DateTime.Now.Millisecond);
            engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope);
            Console.WriteLine(DateTime.Now.Millisecond);
            engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);
            Console.WriteLine(DateTime.Now.Millisecond);

            object thisBoxed = MainV2.cs;
            Type test = thisBoxed.GetType();

            foreach (var field in test.GetProperties())
            {
                // field.Name has the field's name.
                object fieldValue;
                try
                {
                    fieldValue = field.GetValue(thisBoxed, null); // Get value
                }
                catch { continue; }

                // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
                TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());

                items.Add(field.Name);
            }
        }
Exemple #8
0
        private void Start()
        {
            engine = Python.CreateEngine();
            engine.Runtime.LoadAssembly(typeof(GameObject).Assembly);

            engine.Runtime.LoadAssembly(typeof(Image).Assembly);
            //engine.ImportModule("");
            scope = engine.CreateScope();
            scope.SetVariable("pyConsole", pyConsole);
            engine.Execute(pythonScript, scope);
            //var scope = engine.ExecuteFile(path);
            int counter = scope.GetVariable <int>("counter");

            Debug.Log(counter);

            float timeBackup = scope.GetVariable <float>("timeBackup");

            Debug.Log(timeBackup);

            Debug.LogError("Error test");

            Debug.LogWarning("warning\nTest");

            //TestInstance();
            //TestInstance();


            //GameObject.Find("Player").transform.GetChild(0).GetComponent("MeshRenderer").sharedMaterial.color = Color.black;
            //GameObject.Find("Player").transform.localRotation = Quaternion.Euler(0, 0, 90);
            //Camera.main.transform.position = new Vector3(2,2,-5);

            //string variables = string.Join(",", scope.GetVariableNames().ToArray());
            //Debug.Log("variables: " + variables);
        }
Exemple #9
0
        public Script(bool redirectOutput = false)
        {
            Dictionary <string, object> options = new Dictionary <string, object>();

            options["Debug"] = true;

            if (engine != null)
            {
                engine.Runtime.Shutdown();
            }

            engine = Python.CreateEngine(options);
            scope  = engine.CreateScope();

            var all = System.Reflection.Assembly.GetExecutingAssembly();

            engine.Runtime.LoadAssembly(all);
            scope.SetVariable("MAV", MainV2.comPort);
            scope.SetVariable("cs", MainV2.comPort.MAV.cs);
            scope.SetVariable("Script", this);
            scope.SetVariable("mavutil", this);
            scope.SetVariable("Joystick", MainV2.joystick);

            engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope);
            engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);

            if (redirectOutput)
            {
                //Redirect output through this writer
                //this writer will not actually write to the memorystreams
                OutputWriter = new Utilities.StringRedirectWriter();
                engine.Runtime.IO.SetErrorOutput(new MemoryStream(), OutputWriter);
                engine.Runtime.IO.SetOutput(new MemoryStream(), OutputWriter);
            }
            else
            {
                OutputWriter = null;
            }

            /*
             * object thisBoxed = MainV2.comPort.MAV.cs;
             * Type test = thisBoxed.GetType();
             *
             * foreach (var field in test.GetProperties())
             * {
             *  // field.Name has the field's name.
             *  object fieldValue;
             *  try
             *  {
             *      fieldValue = field.GetValue(thisBoxed, null); // Get value
             *  }
             *  catch { continue; }
             *
             *  // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
             *  TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());
             *
             *  items.Add(field.Name);
             * }
             */
        }
Exemple #10
0
        public Script(bool redirectOutput = false)
        {
            Dictionary<string, object> options = new Dictionary<string, object>();
            options["Debug"] = true;

            if (engine != null)
                engine.Runtime.Shutdown();

            engine = Python.CreateEngine(options);

            var paths = engine.GetSearchPaths();
            paths.Add(Settings.GetRunningDirectory() + "Lib.zip");
            engine.SetSearchPaths(paths);

            scope = engine.CreateScope();

            var all = System.Reflection.Assembly.GetExecutingAssembly();
            engine.Runtime.LoadAssembly(all);
            scope.SetVariable("MAV", MainV2.comPort);
            scope.SetVariable("cs", MainV2.comPort.MAV.cs);
            scope.SetVariable("Script", this);
            scope.SetVariable("mavutil", this);
            scope.SetVariable("Joystick", MainV2.joystick);

            engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope);
            engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);

            if (redirectOutput)
            {
                //Redirect output through this writer
                //this writer will not actually write to the memorystreams
                OutputWriter = new Utilities.StringRedirectWriter();
                engine.Runtime.IO.SetErrorOutput(new MemoryStream(), OutputWriter);
                engine.Runtime.IO.SetOutput(new MemoryStream(), OutputWriter);
            }
            else
                OutputWriter = null;

            /*
            object thisBoxed = MainV2.comPort.MAV.cs;
            Type test = thisBoxed.GetType();

            foreach (var field in test.GetProperties())
            {
                // field.Name has the field's name.
                object fieldValue;
                try
                {
                    fieldValue = field.GetValue(thisBoxed, null); // Get value
                }
                catch { continue; }

                // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
                TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());

                items.Add(field.Name);
            }
             */
        }
        private void callPythonCode()
        {
            var options = new Dictionary <string, object>();

            options["Frames"]     = true;
            options["FullFrames"] = true;

            //create ironpython engine and scope
            Microsoft.Scripting.Hosting.ScriptEngine py    = Python.CreateEngine(options);
            Microsoft.Scripting.Hosting.ScriptScope  scope = py.CreateScope();

            //add python folder to pythonpath
            string pythonCodePath      = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/";
            string pyGDPPath           = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/pyGDP-master/";
            string OWSPath             = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/owslib/";
            string owslibPath          = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/OWS/OWSLib-0.8.6/owslib/";
            string libPath             = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/Lib/";
            ICollection <string> paths = py.GetSearchPaths();

            paths.Add(pythonCodePath);
            paths.Add(pyGDPPath);
            paths.Add(OWSPath);
            paths.Add(owslibPath);
            paths.Add(libPath);
            py.SetSearchPaths(paths);

            //store variables in scope
            scope.SetVariable("futOne", futOne);
            scope.SetVariable("futTwo", futTwo);
            scope.SetVariable("futThree", futThree);
            scope.SetVariable("futFour", futFour);
            scope.SetVariable("futFive", futFive);
            scope.SetVariable("futSix", futSix);
            scope.SetVariable("histOne", histOne);
            scope.SetVariable("histTwo", histTwo);
            scope.SetVariable("filePath", filePath);

            //run code
            py.ExecuteFile(Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/module1.py", scope);

            string outputPathF2 = scope.GetVariable("outputPathF2").ToString();
            string outputPathH1 = scope.GetVariable("outputPathH1").ToString();

            //retrieve climate data
            filePath = filePath.Remove(filePath.Length - 9);

            string    urlF2     = "http://cida.usgs.gov:80/gdp/process/RetrieveResultServlet?id=" + outputPathF2;
            WebClient webClient = new WebClient();

            webClient.DownloadFile(urlF2, @filePath + "FutureClimateData.csv");

            string    urlH1      = "http://cida.usgs.gov:80/gdp/process/RetrieveResultServlet?id=" + outputPathH1;
            WebClient webClient2 = new WebClient();

            webClient2.DownloadFile(urlH1, @filePath + "HistoricalClimateData.csv");

            return;
        }
        private void Start()
        {
            engine = Python.CreateEngine();
            engine.Runtime.LoadAssembly(typeof(GameObject).Assembly);

            scope = engine.CreateScope();
            scope.SetVariable("pyConsole", pyConsole);
            scope.SetVariable("unityEvents", unityMethodsEvents);
            engine.Execute(pythonScript, scope);
        }
Exemple #13
0
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptScope  s  = py.CreateScope();

            py.Execute(
                @"import numpy as np 
    incomes = np.random.normal(27000, 15000, 10000) 
    x = np.mean(incomes)"
                , s);
        }
 private void InitPythonPlugin(Package p, ref Microsoft.Scripting.Hosting.ScriptEngine engine, ref Microsoft.Scripting.Hosting.ScriptScope scope)
 {
     if (System.IO.File.Exists(p.Path + "\\__init__.py"))
     {
         engine.ExecuteFile(p.Path + "\\__init__.py", scope);
     }
     else
     {
         throw new InvalidOperationException("Unable to find file __init__.py");
     }
 }
Exemple #15
0
        public Script(bool redirectOutput = false)
        {
            Dictionary<string, object> options = new Dictionary<string, object>();
            options["Debug"] = true;

            if (engine != null)
                engine.Runtime.Shutdown();

            engine = Python.CreateEngine(options);
            var paths = engine.GetSearchPaths();
            paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib"); //Allows for additional libraries from IronPython. Requires download from https://ironpython.codeplex.com/releases/view/90087
            engine.SetSearchPaths(paths);
            scope = engine.CreateScope();

            var all = System.Reflection.Assembly.GetExecutingAssembly();
            engine.Runtime.LoadAssembly(all);
            scope.SetVariable("MAV", MainV2.comPort);
            scope.SetVariable("cs", MainV2.comPort.MAV.cs);
            scope.SetVariable("Script", this);
            scope.SetVariable("mavutil", this);

            //engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope); //Unneeded testing
            //engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);

            if (redirectOutput)
            {
                //Redirect output through this writer
                //this writer will not actually write to the memorystreams
                OutputWriter = new Utilities.StringRedirectWriter();
                engine.Runtime.IO.SetErrorOutput(new MemoryStream(), OutputWriter);
                engine.Runtime.IO.SetOutput(new MemoryStream(), OutputWriter);
            }
            else
                OutputWriter = null;

            object thisBoxed = MainV2.comPort.MAV.cs;
            Type test = thisBoxed.GetType();

            foreach (var field in test.GetProperties())
            {
                // field.Name has the field's name.
                object fieldValue;
                try
                {
                    fieldValue = field.GetValue(thisBoxed, null); // Get value
                }
                catch { continue; }

                // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
                TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());

                items.Add(field.Name);
            }
        }
Exemple #16
0
        public LevelLoader(string levelSource)
        {
            TileExpressions  = new Dictionary <int, string>();
            this.levelSource = levelSource;

            scriptEngine = Python.CreateEngine();
            scriptEngine.Runtime.LoadAssembly(Assembly.GetExecutingAssembly());
            scriptEngine.Runtime.LoadAssembly(Assembly.GetAssembly(typeof(Microsoft.Xna.Framework.Vector2)));

            ParseTiles();
        }
Exemple #17
0
 static void Main(string[] args)
 {
     Microsoft.Scripting.Hosting.ScriptEngine pythonEngine =
         IronPython.Hosting.Python.CreateEngine();
     // We execute this script from Visual Studio
     // so the program will be executed from bin\Debug or bin\Release
     Microsoft.Scripting.Hosting.ScriptSource pythonScript =
         pythonEngine.CreateScriptSourceFromFile("..\\..\\python.py");
     Console.Beep(); //Plays Beep before running python
     pythonScript.Execute();
     ReadLine();
 }
        public bool IronPython(Parameter parameter)
        {
            StringBuilder statementBuilder = new StringBuilder()
                                             .AppendLine("[")
                                             .AppendJoin("," + Environment.NewLine, parameter.Statements)
                                             .AppendLine("]");

            Microsoft.Scripting.Hosting.ScriptEngine engine = global::IronPython.Hosting.Python.CreateEngine();

            int[] results = engine.Execute <IronPython.Runtime.List>(statementBuilder.ToString()).Select(Convert.ToInt32).ToArray();

            return(Assert(results, parameter.Sum));
        }
Exemple #19
0
        static IPyInterface()
        {
            //Create the python execution engine
            engine = IronPython.Hosting.Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptScope scriptScope = engine.CreateScope();

            //Link to the scripts that create the Beach_Interface object
            string strInitialize = "import Interface";
            string strGet_interface = "Interface.Interface";

            //Return the Beach_Interface object
            engine.Execute(strInitialize, scriptScope);
            ipyInterface = engine.Execute(strGet_interface, scriptScope);
        }
Exemple #20
0
        static IPyInterface()
        {
            //Create the python execution engine
            engine = IronPython.Hosting.Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptScope scriptScope = engine.CreateScope();

            //Link to the scripts that create the Beach_Interface object
            string strInitialize    = "import Interface";
            string strGet_interface = "Interface.Interface";

            //Return the Beach_Interface object
            engine.Execute(strInitialize, scriptScope);
            ipyInterface = engine.Execute(strGet_interface, scriptScope);
        }
Exemple #21
0
        public override void Execute(string src, Uri uri, HttpListenerContext p, WebConfig wc, StreamWriter sw)
        {
            Microsoft.Scripting.Hosting.ScriptEngine py = IronRuby.Ruby.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptScope  s  = py.CreateScope();

            var sapi = new StandardScriptApi(uri, p, sw);

            foreach (var item in sapi.Variables)
            {
                s.SetVariable(item.Key, item.Value);
            }

            py.Execute(src, s);
        }
Exemple #22
0
        private void ConnectAndExecute(IJob job, Microsoft.Scripting.Hosting.ScriptEngine scriptEngine, bool abortOnFailure)
        {
            using (IDbConnection dbConnection = connectionProvider.NewConnection)
            {
                var connectionTimer = new PerformanceTimer().Start();
                SetupAndOpenDatabaseConnection(job, dbConnection);
                var formatter = new LogFormatter().ForJob(job.Name, job.ConnectionName);
                logger.LogInformation(formatter.TextForJob(connectionTimer.StopAndGetElapsedTime().ToFormattedString(), context.RemainingTime.ToFormattedString(), "Opened Database Connection"));

                using (IDbTransaction transaction = dbConnection.BeginTransaction(IsolationLevel.ReadCommitted))
                {
                    var jobTimer = new PerformanceTimer().Start();
                    try
                    {
                        var result = job.Execute(new Resources
                        {
                            JobLoader      = jobLoader,
                            ScriptEngine   = scriptEngine,
                            DbTransaction  = transaction,
                            Logger         = logger,
                            LogFormatter   = formatter,
                            AbortOnFailure = abortOnFailure,
                            Context        = context
                        });
                        var elapsedTime = jobTimer.StopAndGetElapsedTime();
                        if (result.Success)
                        {
                            logger.LogInformation(formatter.TextForJob(elapsedTime.ToFormattedString(), context.RemainingTime.ToFormattedString(), result.Message));
                            transaction.Commit();
                        }
                        else
                        {
                            throw new Exception(result.Message);
                        }
                    }
                    catch (Exception e)
                    {
                        transaction.Rollback();
                        var elapsedTime = jobTimer.StopAndGetElapsedTime();
                        logger.LogWarning(formatter.TextForJob(elapsedTime.ToFormattedString(), string.Empty, "EXCEPTION - Changes rolled back"));
                        dbConnection.Close();
                        logger.LogError(e.ToString());
                        throw e;
                    }
                }
                dbConnection.Close();
                logger.LogInformation(formatter.TextForJob(string.Empty, string.Empty, "Closed Database Connection"));
            }
        }
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptScope  s  = py.CreateScope();

            // add paths to where your libs are installed
            var libs = new[] { @"c:\path\to\lib1", @"c:\path\to\lib2" };

            py.SetSearchPaths(libs);
            py.Execute(
                @"import numpy as np 
    incomes = np.random.normal(27000, 15000, 10000) 
    x = np.mean(incomes)"
                , s);
        }
Exemple #24
0
        public bool IronPython(Parameter parameter)
        {
            Microsoft.Scripting.Hosting.ScriptEngine engine = global::IronPython.Hosting.Python.CreateEngine();

            List <int> results = new List <int>(parameter.Statements.Length);

            foreach (string statement in parameter.Statements)
            {
                int result = engine.Execute <int>(statement);

                results.Add(result);
            }

            return(Assert(results, parameter.Sum));
        }
Exemple #25
0
        private static PyAst.PythonAst ParsePythonSource(Microsoft.Scripting.Hosting.ScriptEngine engine, string code)
        {
            var src          = engine.CreateScriptSourceFromString(code);
            var sourceUnit   = Microsoft.Scripting.Hosting.Providers.HostingHelpers.GetSourceUnit(src);
            var langContext  = Microsoft.Scripting.Hosting.Providers.HostingHelpers.GetLanguageContext(engine);
            var compilerCtxt = new Microsoft.Scripting.Runtime.CompilerContext(
                sourceUnit,
                langContext.GetCompilerOptions(),
                Microsoft.Scripting.ErrorSink.Default);
            var parser = IronPython.Compiler.Parser.CreateParser(
                compilerCtxt,
                (IronPython.PythonOptions)langContext.Options
                );

            return(parser.ParseFile(false));
        }
Exemple #26
0
        public Script()
        {
            Dictionary <string, object> options = new Dictionary <string, object>();

            options["Debug"] = true;

            if (engine != null)
            {
                engine.Runtime.Shutdown();
            }

            engine = Python.CreateEngine(options);
            scope  = engine.CreateScope();

            var all = System.Reflection.Assembly.GetExecutingAssembly();

            engine.Runtime.LoadAssembly(all);
            scope.SetVariable("MAV", MainV2.comPort);
            scope.SetVariable("cs", MainV2.comPort.MAV.cs);
            scope.SetVariable("Script", this);
            scope.SetVariable("mavutil", this);

            engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope);
            engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);


            object thisBoxed = MainV2.comPort.MAV.cs;
            Type   test      = thisBoxed.GetType();

            foreach (var field in test.GetProperties())
            {
                // field.Name has the field's name.
                object fieldValue;
                try
                {
                    fieldValue = field.GetValue(thisBoxed, null); // Get value
                }
                catch { continue; }

                // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
                TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());

                items.Add(field.Name);
            }
        }
Exemple #27
0
        public override void Initialize()
        {
            Func <TreeNode <string>, JObject> nodeToJObject = (node) =>
            {
                JObject obj = new JObject();
                TreeNode <string> .TreeNodeToJson(node, obj);

                return(obj);
            };


            _scriptEngine = Python.CreateEngine();
            _scope        = _scriptEngine.CreateScope();



            //  Execute main script
            {
                string entryFile = Data.GetValue("entry");
                var    src       = _scriptEngine.CreateScriptSourceFromFile(entryFile);

                Logger.Info("Main script({0}) loading...", Path.GetFileName(entryFile));
                src.Execute(_scope);


                //  Setting global variables
                SetVariable("ScriptName", Name);                            //  globalObjects의 이름
                SetVariable("RoseApi", _scriptApi);                         //  ScriptAPI instance
                SetVariable("ServerConfig", nodeToJObject(Starter.Config)); //  Config 전체
                SetVariable("ScriptConfig", nodeToJObject(Data));           //  globalObjects에 정의된 data 항목


                //  Predefined function
                FnRoseEntry              = GetVariable("roseEntry");
                FnBeforeRequestHandling  = GetVariable("beforeRequestHandling");    //  Request 핸들러
                FnBeforeResponseHandling = GetVariable("beforeResponseHandling");   //  Response 핸들러


                //  Call entry function
                if (FnRoseEntry != null)
                {
                    FnRoseEntry();
                }
            }
        }
    public void runScript()
    {
        String path   = @"c:\pythonSpeedTest.py";
        var    source = System.IO.File.ReadAllText(path);

        Microsoft.Scripting.Hosting.ScriptEngine py    = Python.CreateEngine();
        Microsoft.Scripting.Hosting.ScriptScope  scope = py.CreateScope();
        var paths = py.GetSearchPaths();

        paths.Add(@"c:\Program Files (x86)\IronPython 2.7\Lib");
        py.SetSearchPaths(paths);
        try {
            py.Execute(source);
        }catch (Exception ex) {
            Console.WriteLine("Error occured in python script\n" + ex);
            Console.ReadKey();
            return;
        }
    }
        /// <summary>
        /// Imports the chosen image
        /// </summary>
        /// <param name="imgpath">path to image</param>
        /// <param name="scriptpath">script path</param>
        /// <returns></returns>
        public Bitmap Load(string imgpath, string scriptpath)
        {
            py = Python.CreateEngine();
            s  = py.CreateScope();

            path   = imgpath;
            img    = new Bitmap(4, 4);
            script = scriptpath;
            if (scriptpath.Length > 100)
            {
                py.Execute(script, s);
            }
            else
            {
                py.ExecuteFile(script, s);
            }
            LoadImg();
            return(img);
        }
Exemple #30
0
        public bool IronPython(Parameter parameter)
        {
            Microsoft.Scripting.Hosting.ScriptEngine engine = global::IronPython.Hosting.Python.CreateEngine();

            Microsoft.Scripting.Hosting.ScriptScope scope = engine.CreateScope();

            scope.SetVariable("n", parameter.Numbers);

            List <int> results = new List <int>(parameter.Numbers.Length);

            foreach (int number in parameter.Numbers)
            {
                int result = engine.Execute <int>(parameter.Statements[number], scope);

                results.Add(result);
            }

            return(Assert(results, parameter.Sum));
        }
        public Script()
        {
            Dictionary<string, object> options = new Dictionary<string, object>();
            options["Debug"] = true;

            if (engine != null)
                engine.Runtime.Shutdown();

            engine = Python.CreateEngine(options);
            scope = engine.CreateScope();

            var all = System.Reflection.Assembly.GetExecutingAssembly();
            engine.Runtime.LoadAssembly(all);
            scope.SetVariable("MAV", MainV2.comPort);
            scope.SetVariable("cs", MainV2.comPort.MAV.cs);
            scope.SetVariable("Script", this);
            scope.SetVariable("mavutil", this);

            engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope);
            engine.CreateScriptSourceFromString("print cs.roll").Execute(scope);

            object thisBoxed = MainV2.comPort.MAV.cs;
            Type test = thisBoxed.GetType();

            foreach (var field in test.GetProperties())
            {
                // field.Name has the field's name.
                object fieldValue;
                try
                {
                    fieldValue = field.GetValue(thisBoxed, null); // Get value
                }
                catch { continue; }

                // Get the TypeCode enumeration. Multiple types get mapped to a common typecode.
                TypeCode typeCode = Type.GetTypeCode(fieldValue.GetType());

                items.Add(field.Name);
            }
        }
Exemple #32
0
        static void Main(string[] args)
        {
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();

            ICollection <string> searchPaths = pythonEngine.GetSearchPaths();

            searchPaths.Add("..\\..");
            pythonEngine.SetSearchPaths(searchPaths);

            Microsoft.Scripting.Hosting.ScriptScope scope = IronPython.Hosting.Python.ImportModule(pythonEngine, "HelloWorldModule");

            dynamic printHelloWorldFunction = scope.GetVariable("PrintHelloWorld");

            printHelloWorldFunction();

            dynamic printMessageFunction = scope.GetVariable("PrintMessage");

            printMessageFunction("Goodbye!");

            dynamic addFunction = scope.GetVariable("Add");

            System.Console.Out.WriteLine("The sum of 1 and 2 is " + addFunction(1, 2));
        }
Exemple #33
0
 private void InitializeIronPython()
 {
     pyEngine = IronPython.Hosting.Python.CreateEngine();
     pyScope = pyEngine.CreateScope();
     pyScope.SetVariable("qst", QST);
 }
Exemple #34
0
 static Directive()
 {
     _engine = Python.CreateEngine();
 }
Exemple #35
0
 public PythonScriptEngine()
 {
     engine = Python.CreateEngine();
     scope  = engine.CreateScope();
 }
Exemple #36
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            textBox.Highlighter = Highlighters.Ruby;
            textBox.Images = templateBMPs;
            engine = IronRuby.Ruby.CreateEngine();
            ui = new UI(this);
            scope = engine.CreateScope();
            scope.SetVariable("ui", ui);

            // Ctrl + R で今表示されているスクリプトを実行
            // Ctrl + Esc で実行終了
            // Ctrl + RPrintScreen でスクリーンショットを撮る
            AddHotKeyAction(MOD_WIN, Keys.S, "スローモーションで実行", () => { ui.slowPlayFlag = true; Run(textBox.Text); });
            AddHotKeyAction(MOD_WIN, Keys.Q, "実行停止", () => 停止SToolStripMenuItem_Click(null, null));
            AddHotKeyAction(MOD_CONTROL, Keys.PrintScreen, "スクリーンショットを撮る", () => new BlackForm().takeScreenshot(this));

            LoadConfigData();
        }
Exemple #37
0
 static void Main(string[] args)
 {
     Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
     Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString("print 'Hello World!'");
     pythonScript.Execute();
 }