示例#1
0
        public void RunScripts()
        {
            try
            {
                foreach (string[] str in localScripts)
                {
                    string       code         = str[0];
                    byte[]       encodedBytes = Convert.FromBase64String(code);
                    UTF8Encoding utf8         = new UTF8Encoding();
                    Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
                    Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(utf8.GetString(encodedBytes));
                    var answer = pythonScript.Execute();                    //change later to allow for more types

                    byte[] answerBytes = utf8.GetBytes(answer.ToString());
                    str[1] = Convert.ToBase64String(answerBytes);
                }
            }
            catch (RuntimeBinderException e)
            {
                MessageBox.Show("There was an error with the scripts you wanted me to run");
            }
            catch (UnboundNameException e)
            {
                MessageBox.Show("Please double check that input was put in correctly");
            }
        }
示例#2
0
    // Pass the script text to the interpreter and display results
    private void Intepret(string text_to_interpret)
    {
        object result = null;

        try {
            Undo.RegisterSceneUndo("script");
            var scriptSrc = _ScriptEngine.CreateScriptSourceFromString(text_to_interpret);
            _historyText += "\n";
            _historyText += text_to_interpret;
            _historyText += "\n";
            result        = scriptSrc.Execute(_ScriptScope);
        }
        // Log exceptions to the console too
        catch (System.Exception e) {
            Debug.LogException(e);
            _historyText += "\n";
            _historyText += "#  " + e.Message + "\n";
        }
        finally {
            // grab the __print_buffer stringIO and get its contents
            var print_buffer = _ScriptScope.GetVariable("__print_buffer");
            var gv           = _ScriptEngine.Operations.GetMember(print_buffer, "getvalue");
            var st           = _ScriptEngine.Operations.Invoke(gv);
            var src          = _ScriptEngine.CreateScriptSourceFromString("__print_buffer = sys.stdout = StringIO()");
            src.Execute(_ScriptScope);
            if (st.ToString().Length > 0)
            {
                _historyText += "";
                foreach (string l in st.ToString().Split('\n'))
                {
                    _historyText += "  " + l + "\n";
                }
                _historyText += "\n";
            }
            // and print the last value for single-statement evals
            if (result != null)
            {
                _historyText += "#  " + result.ToString() + "\n";
            }
            int lines = _historyText.Split('\n').Length;
            _historyScroll.y += (lines * 19);
            Repaint();
        }
    }
示例#3
0
        public static ScriptingHosting.ScriptSource CreateScriptSourceFromFile(
            ScriptingHosting.ScriptEngine engine, string sourceFilePath
            )
        {
            var sourceText = TextFileUtil.ReadAllText(sourceFilePath);

            var scriptSource = engine.CreateScriptSourceFromString(sourceText, sourceFilePath, MSScripting.SourceCodeKind.Statements);

            return(scriptSource);
        }
示例#4
0
    void Exec()
    {
        print("Exec");
        var source = engine.CreateScriptSourceFromString(script);

        try {
            source.Execute(scope);
        } catch (Microsoft.Scripting.SyntaxErrorException e) {
            Debug.LogError(e);
        } catch (System.Exception e) {
            Debug.LogError(e);
        }
    }
示例#5
0
    public PythonScriptCreator(TextAsset PythonFile)
    {
        //TextAssetからstringに変換
        this.script = PythonFile.text;

        this.scriptEngine = Python.CreateEngine();

        scriptEngine.Runtime.LoadAssembly(typeof(GameObject).Assembly);
        this.scriptScope = scriptEngine.CreateScope();

        //stringを渡すとpythonスクリプトとして読み込んでくれる
        this.scriptSource = scriptEngine.CreateScriptSourceFromString(script);
    }
示例#6
0
 public void ExecuteScript(string sourceString)
 {
     Microsoft.Scripting.Hosting.ScriptSource sourceCode =
         _engine.CreateScriptSourceFromString(sourceString);
     try
     {
         sourceCode.Execute(_mainScope);
     }
     catch (Exception e)
     {
         _logToConsole(e.Message);
     }
 }
示例#7
0
    // initialization logic (it's Unity, so we don't do this in the constructor!
    public void OnEnable()
    {
        PythonTools window = (PythonTools)EditorWindow.GetWindow(typeof(PythonTools));

        window.titleContent = new GUIContent("Python Console", "Execute Unity functions via IronPython");

        // pure gui stuff
        consoleStyle.normal.textColor = Color.cyan;
        consoleStyle.margin           = new RectOffset(20, 10, 10, 10);
        historyStyle.normal.textColor = Color.white;
        historyStyle.margin           = new RectOffset(20, 10, 10, 10);

        // load up the hosting environment
        _ScriptEngine = IronPython.Hosting.Python.CreateEngine();
        _ScriptScope  = _ScriptEngine.CreateScope();

        // load the assemblies for unity, using types
        // to resolve assemblies so we don't need to hard code paths
        _ScriptEngine.Runtime.LoadAssembly(typeof(PythonFileIOModule).Assembly);
        _ScriptEngine.Runtime.LoadAssembly(typeof(GameObject).Assembly);
        _ScriptEngine.Runtime.LoadAssembly(typeof(Editor).Assembly);
        string dllpath = System.IO.Path.GetDirectoryName(
            (typeof(ScriptEngine)).Assembly.Location).Replace(
            "\\", "/");
        // load needed modules and paths
        StringBuilder init = new StringBuilder();

        init.AppendLine("import sys");
        init.AppendFormat("sys.path.append(\"{0}\")\n", dllpath + "/Lib");
        init.AppendFormat("sys.path.append(\"{0}\")\n", dllpath + "/DLLs");
        init.AppendLine("import UnityEngine as unity");
        init.AppendLine("import UnityEditor as editor");
        init.AppendLine("from cStringIO import StringIO");
        init.AppendLine("unity.Debug.Log(\"Python console initialized\")");
        init.AppendLine("__print_buffer = sys.stdout = StringIO()");
        var ScriptSource = _ScriptEngine.CreateScriptSourceFromString(init.ToString());

        ScriptSource.Execute(_ScriptScope);
    }
        public ScriptResult run(Script script, Feature feature, FilterEnv env)
        {
            if (!string.IsNullOrWhiteSpace(script.Language) &&
                !script.Language.ToLowerInvariant().Contains("python"))
            {
                return(new ScriptResult(script.Code));
            }

            scope.SetVariable("feature", feature);
            scope.SetVariable("env", env);

            StringBuilder code = new StringBuilder();

            foreach (Script sc in scripts)
            {
                code.Append(sc.Code);
            }
            code.Append(script.Code);

            ScriptSource source2 = engine.CreateScriptSourceFromString(code.ToString(), SourceCodeKind.AutoDetect);
            var          res2    = source2.Execute(scope);

            return(new ScriptResult(res2));
        }
        public Script(bool redirectOutput = false, DataDisplay datadisplayer = null)
        {
            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");
            paths.Add(Settings.GetRunningDirectory() + "lib");
            paths.Add(Settings.GetRunningDirectory());
            engine.SetSearchPaths(paths);

            scope = engine.CreateScope();


            var all  = System.Reflection.Assembly.GetExecutingAssembly();
            var asss = AppDomain.CurrentDomain.GetAssemblies();

            foreach (var ass in asss)
            {
                engine.Runtime.LoadAssembly(ass);
            }

            scope.SetVariable("Ports", MainV2.Comports);
            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);
            //added classes for DAS
            dataDisplay = datadisplayer;
            scope.SetVariable("DAS", dataDisplay);


            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);
             * }
             */
        }