Пример #1
0
    public void ExecuteScript()
    {
        ReleaseAnyVariable();

        if (engine == null)
        {
            engine = UnityPython.CreateEngine();
        }
        runtime = engine.Runtime;
        scope   = runtime.CreateScope();

        scripts.ForEach(script => {
            var scriptContent = script.GetScriptHeader();
            scriptContent    += script.script;
            // create script source from content
            var source = engine.CreateScriptSourceFromString(scriptContent);
            try
            {
                // execute python script
                source.Execute(scope);
            }
            catch (System.Exception exc)
            {
                Debug.LogError(exc);
            }
        });

        runtime.Shutdown();
        this.stoppable = false;
    }
Пример #2
0
    public void ExecuteScript()
    {
        // release any variable
        ReleaseAnyVariable();

        runtime = engine.Runtime;
        scope   = runtime.CreateScope();

        var scriptContent = GetScriptHeader();

        scriptContent += script;

        // create script source from content
        var source = engine.CreateScriptSourceFromString(scriptContent);

        // include unity variables
        IncludeVariables();
        // updated unity variables
        UpdateUnityVariables();
        // include python variables
        IncludePythonVariables();
        try
        {
            // execute python script
            source.Execute(scope);
            // store python variables
            StorePythonVariables();
        }
        catch (System.Exception exc)
        {
            Debug.LogError(exc);
        }
        runtime.Shutdown();
        this.stoppable = false;
    }
Пример #3
0
        public void DefaultEngine_GetDefaultEngineTest()
        {
            ScriptRuntime defaultRuntime = CreateRuntime();
            ScriptScope   scope          = defaultRuntime.CreateScope();
            //scope.DefualtEngine

            // Bug - Spec versus Code - DefaultEngine is currently called 'scope.Engine'
        }
Пример #4
0
        protected ScriptManager()
        {
            Instance = this;

            messageReady = new AutoResetEvent(false);

            messageHandlers      = new Dictionary <uint, MessageDelegate>();
            eventMessageHandlers = new Dictionary <uint, Dictionary <uint, MessageDelegate> >();
            messageQueue         = new ConcurrentQueue <Message>();

            scriptApi = new ScriptApi();
            scriptApi.MessageHandler = (IScriptMessageHandler)this;
            //scriptApi.MessageHandler.HandleMessage = HandleMessage;
            //scriptApi.MessageHandler.HandleMessageEvent = HandleMessageEvent;

            scriptThread = new Thread(ScriptThreadStart);

            // it is possible to do this via configuration
            // i need to find an example to implement

            //engineRuntime = ScriptRuntime.CreateFromConfiguration();
            //engine = engineRuntime.GetEngine("python");
            engine        = Python.CreateEngine();
            engineRuntime = engine.Runtime;

            engineRuntime.LoadAssembly(typeof(string).Assembly);
            engineRuntime.LoadAssembly(typeof(Uri).Assembly);
            engineRuntime.LoadAssembly(this.GetType().Assembly);

            //engineScope = engine.CreateModule("Api");
            //engineScope.SetVariable("MessageHandler", scriptApi.MessageHandler);

            // Dictionary<string, object> mh = new Dictionary<string, object>();
            // mh.Add("__all__", new string[] { "HandleMessage", "HandleMessageEvent" });
            // mh.Add("__dir__", new string[] { "HandleMessage", "HandleMessageEvent" });
            // mh.Add("__name__", "MessageHandler");
            // mh.Add("HandleMessage", ((IScriptMessageHandler)this).HandleMessage);
            // mh.Add("HandleMessageEvent", ((IScriptMessageHandler)this).HandleMessageEvent);

            //ScriptScope modScope = engine.CreateScope(mh);
            // modScope.SetVariable("HandleMessage", ((IScriptMessageHandler)this).HandleMessage);
            // modScope.SetVariable("HandleMessageEvent", ((IScriptMessageHandler)this).HandleMessageEvent);

            //Scope messageMod = HostingHelpers.GetScope(modScope);

            //modScope = engine.CreateScope();
            //modScope.SetVariable("MessageHandler", messageMod);

            //Scope apiModule = HostingHelpers.GetScope(modScope);

            //engineRuntime.Globals.SetVariable("Api", apiModule);


            engineScope = engineRuntime.CreateScope();

            scriptThread.Start();
        }
        public IronPythonScriptEngine()
        {
            runtime = engine.Runtime;
            runtime.LoadAssembly(Assembly.GetAssembly(typeof(Mogre.Vector3)));
            scope = runtime.CreateScope();

            // install built-in scripts
            install(new Script(builtin));
        }
Пример #6
0
        public Ruby_Engine()
        {
            runtime = IronRuby.Ruby.CreateRuntime();
            engine  = runtime.GetEngine("Ruby");
            scope   = runtime.CreateScope();

            execute(@"require 'mscorlib'
require 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL'");
            require_assembly(System.Reflection.Assembly.GetExecutingAssembly());
        }
Пример #7
0
        private ScriptScope PrepareScriptScopeByPath(String path)
        {
            ScriptScope scriptScope = _scriptRuntime.CreateScope();

            scriptScope.SetVariable("Session", _sessionProxy.GetTransparentProxy());
            scriptScope.SetVariable("Server", _serverProxy.GetTransparentProxy());
            scriptScope.SetVariable("CurrentSession", _sessionProxy.GetTransparentProxy());
            scriptScope.SetVariable("CurrentServer", _serverProxy.GetTransparentProxy());

            return(_scriptScopes[path] = scriptScope);
        }
Пример #8
0
        public void RunProgram()
        {
            engine  = Python.CreateEngine();
            runtime = engine.Runtime;
            scope   = runtime.CreateScope();

            RunExpression();

            RunInScope();

            RunFromFile();
        }
Пример #9
0
        public Scripting()
        {
            Host   = Python.CreateRuntime();
            Scope  = Host.CreateScope();
            Engine = Host.GetEngine("Python");

            PacketHooks      = new Dictionary <NSCommand, List <PacketHookCall> >();
            UpdateHooks      = new List <UpdateHookCall>();
            ChatHooks        = new List <ChatHookCall>();
            ChatCommandHooks = new Dictionary <string, List <ChatCommandHookCall> >();
            NameFormatHooks  = new List <NameFormatHookCall>();
            PlayerXPHooks    = new List <PlayerXPHookCall>();
        }
Пример #10
0
        /// <summary>
        /// Creates a new scope, adding any convenience globals and modules.
        /// </summary>
        public static ScriptScope CreateScope(ScriptRuntime runtime)
        {
            var scope = runtime.CreateScope();

            scope.SetVariable("document", HtmlPage.Document);
            scope.SetVariable("window", HtmlPage.Window);
            if (DynamicApplication.Current != null)
            {
                scope.SetVariable("me", DynamicApplication.Current.RootVisual);
                scope.SetVariable("xaml", DynamicApplication.Current.RootVisual);
            }
            return(scope);
        }
Пример #11
0
        public void CreateScope_InvokeMethodTwiceWithSameGlobals()
        {
            ScriptScopeDictionary dict = new ScriptScopeDictionary();

            ScriptRuntime runTimeOne = CreateRuntime();
            ScriptRuntime runTimeTwo = CreateRuntime();

            dict["foo_1"] = 1000;

            ScriptScope scope1 = runTimeOne.CreateScope(new ObjectDictionaryExpando(dict));
            ScriptScope scope2 = runTimeTwo.CreateScope(new ObjectDictionaryExpando(dict));

            Assert.IsTrue(scope1.IsSimilarButNotSameAs(scope2));
        }
Пример #12
0
        private void ValidateGetItems(ScriptRuntime runtime)
        {
            ScriptScope scope = runtime.CreateScope();

            var dict = new KeyValuePair <string, object>("var1", 1);

            scope.SetVariable(dict.Key, dict.Value);

            TestHelpers.AreEqualCollections <KeyValuePair <string, object> >(new[] { dict }, scope.GetItems());

            var newDict = new KeyValuePair <string, object>("newVar", "newval");

            scope.SetVariable(newDict.Key, newDict.Value);

            TestHelpers.AreEqualCollections <KeyValuePair <string, object> >(new[] { dict, newDict }, scope.GetItems());
        }
Пример #13
0
        static void Main(string[] args)
        {
            var runtimeSetup = Python.CreateRuntimeSetup(new Dictionary <string, object>());

            runtimeSetup.DebugMode = true;

            var runtime = new ScriptRuntime(runtimeSetup);

            var scope = runtime.CreateScope(new Dictionary <string, object> {
                { "name", "Batman" }
            });

            var engine       = runtime.GetEngine("py");
            var scriptSource = engine.CreateScriptSourceFromFile("script.py");
            var compiledCode = scriptSource.Compile();

            compiledCode.Execute(scope);
        }
Пример #14
0
        protected HAPITestBase()
        {
            var ses = CreateSetup();

            ses.HostType   = typeof(TestHost);
            _runtime       = new ScriptRuntime(ses);
            _remoteRuntime = ScriptRuntime.CreateRemote(TestHelpers.CreateAppDomain("Alternate"), ses);

            _runTime = _runtime;// _remoteRuntime;

            _PYEng = _runTime.GetEngine("py");
            _RBEng = _runTime.GetEngine("rb");

            SetTestLanguage();

            _defaultScope = _runTime.CreateScope();
            _codeSnippets = new PreDefinedCodeSnippets();
        }
Пример #15
0
        public bool BeforeRequest(Session session, Rule rule)
        {
            var scope = _runtime.CreateScope();

            scope.SetVariable("session", session);
            scope.SetVariable("rule", rule);

            try
            {
                var result = _code.Execute <bool>(scope);
                RuleLog.Current.AddRule(rule, session, String.Format("Python Script ({0})", session.hostname));
                return(result);
            }
            catch
            {
                RuleLog.Current.AddRule(rule, session, String.Format("Python Exception ({0})", session.hostname));
                return(true);
            }
        }
Пример #16
0
        public CompiledCode GetCompiledScript()
        {
            try
            {
                m_scriptText = GetText();

                if (m_scriptText.IsNullOrBlank())
                {
                    throw new ApplicationException("Cannot load script, file was empty " + m_scriptPath + ".");
                }

                // Configure script engine.
                ScriptTypesEnum scriptType = GetScriptType(m_scriptPath);

                if (scriptType == ScriptTypesEnum.Python)
                {
                    logger.Debug("Compiling IronPython script file from " + m_scriptPath + ".");
                    ScriptRuntime scriptRuntime = IronPython.Hosting.Python.CreateRuntime();
                    ScriptScope   scriptScope   = scriptRuntime.CreateScope("IronPython");
                    CompiledCode  compiledCode  = scriptScope.Engine.CreateScriptSourceFromFile(m_scriptPath).Compile();
                    logger.Debug("IronPython compilation complete.");
                    return(compiledCode);
                    //return scriptScope.Engine.CreateScriptSourceFromString(m_scriptText).Compile();
                }
                else if (scriptType == ScriptTypesEnum.Ruby)
                {
                    logger.Debug("Compiling IronRuby script file from " + m_scriptPath + ".");
                    ScriptRuntime scriptRuntime = IronRuby.Ruby.CreateRuntime();
                    ScriptScope   scriptScope   = scriptRuntime.CreateScope("IronRuby");
                    return(scriptScope.Engine.CreateScriptSourceFromString(m_scriptText).Compile());
                }
                else
                {
                    throw new ApplicationException("ScriptLoader could not compile script, unrecognised proxy script type " + scriptType + ".");
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception GetCompiledScript. " + excp.Message);
                throw;
            }
        }
Пример #17
0
        public void Create_PartialTrust()
        {
            // basic check of running a host in partial trust
            AppDomainSetup info = new AppDomainSetup();

            info.ApplicationBase = TestHelpers.BinDirectory;
            info.ApplicationName = "Test";
            Evidence evidence = new Evidence();

            evidence.AddHost(new Zone(SecurityZone.Internet));
            System.Security.PermissionSet permSet = SecurityManager.GetStandardSandbox(evidence);
            AppDomain newDomain = AppDomain.CreateDomain("test", evidence, info, permSet, null);

            ScriptRuntime runtime = CreateRemoteRuntime(newDomain);
            ScriptScope   scope   = runtime.CreateScope();

            scope.SetVariable("test", "value");

            AppDomain.Unload(newDomain);
        }
Пример #18
0
        internal static ScriptEngine GetScriptEngine()
        {
            ScriptRuntimeSetup Setup = new ScriptRuntimeSetup();

            Setup.LanguageSetups.Add(IronRuby.Ruby.CreateRubySetup());
            Setup.LanguageSetups.Add(IronPython.Hosting.Python.CreateLanguageSetup(null));
            ScriptRuntime RunTime = new ScriptRuntime(Setup);
            ScriptEngine  Engine  = RunTime.GetEngine("py");
            ScriptScope   Scope   = RunTime.CreateScope();

            Assembly MainAssembly = Assembly.GetExecutingAssembly();
            string   RootDir      = Directory.GetParent(MainAssembly.Location).FullName;

            RunTime.LoadAssembly(MainAssembly);
            RunTime.LoadAssembly(typeof(String).Assembly);
            RunTime.LoadAssembly(typeof(Uri).Assembly);
            RunTime.LoadAssembly(typeof(XmlDocument).Assembly);

            Engine.Runtime.TryGetEngine("py", out Engine);
            return(Engine);
        }
Пример #19
0
        public void TestFromFuture_globalScope()
        {
            //string testSrc = "from __future__ import division\nr= 1/2\n";
            string        testSrc     = _codeSnippets[CodeType.ImportFutureDiv];
            ScriptRuntime sr          = _runtime;
            ScriptScope   globalScope = sr.CreateScope();
            ScriptEngine  pyeng       = sr.GetEngine("py");

            //ScriptScope futureScope = pyeng.CreateScope();
            //futureScope.SetVariable("division", true);
            globalScope.SetVariable("division", true);
            sr.Globals.SetVariable("__future__", globalScope);

            ScriptSource source = pyeng.CreateScriptSourceFromString(testSrc, SourceCodeKind.Statements);
            //ScriptScope globalScope = sr.CreateScope();

            object result = source.Execute(globalScope);
            object r2     = globalScope.GetVariable("r");

            Assert.AreEqual((double)r2, 0.5);
        }
Пример #20
0
        public void Create_CallMethodsOnSecondUnloadedAppDomain()
        {
            AppDomain appDomainOne = TestHelpers.CreateAppDomain("AppDomain 1");
            AppDomain appDomainTwo = TestHelpers.CreateAppDomain("AppDomain 2");

            // This throws exception 'System.IO.FileNotFoundException'
            ScriptRuntime scpRunTimeOne = CreateRemoteRuntime(appDomainOne);

            // This should NOT throw an exception
            ScriptRuntime scpRunTimeTwo = CreateRemoteRuntime(appDomainTwo);

            // Unload the AppDomain
            AppDomain.Unload(appDomainOne);

            // This should work fine
            ScriptScope sScpOne = scpRunTimeOne.CreateScope();

            // *** USABILITY *** can be simpler then test plan
            // indicates - perhaps could gather test from other code
            // into one place to do light weight end to end tests.

            // Usability tests - Never Get Here because of earlier exception.
            // Put this in an other peace of code to valid the code.
            sScpOne.SetVariable("foo", 42);
            int          exptRtnVal = 4;
            ScriptEngine pEng       = scpRunTimeTwo.GetEngine("py");
            // Could add this to PreDefinedCodeSnippets
            ScriptSource sSrc = pEng.CreateScriptSourceFromString("a = 1 + 3");
            object       rObj = sSrc.Execute(_testEng.CreateScope());

            Assert.IsNotNull(rObj);
            ScriptScope sScpEng = pEng.CreateScope();
            object      fooObj  = sScpEng.GetVariable("foo");

            Assert.IsTrue(fooObj.Equals(exptRtnVal), "Did the operation work");

            // This should throw AppDomainUnloadedException
            ScriptScope sScpTwo = scpRunTimeTwo.CreateScope();
        }
Пример #21
0
        public void run(bool withLeak)
        {
            //set up script environment
            Dictionary <String, Object> options = new Dictionary <string, object>();

            options["LightweightScopes"] = true;
            ScriptEngine          engine = Python.CreateEngine(options);
            PythonCompilerOptions pco    = (PythonCompilerOptions)engine.GetCompilerOptions();

            pco.Module &= ~ModuleOptions.Optimized;
            engine.SetSearchPaths(new string[] {
                @"C:\Program Files\IronPython 2.7\Lib"
            });
            ScriptRuntime runtime = engine.Runtime;
            ScriptScope   scope   = runtime.CreateScope();
            var           source  = engine.CreateScriptSourceFromString(
                withLeak ? scriptWithLeak : scriptWithoutLeak
                );
            var comped = source.Compile();

            comped.Execute(scope);
            runtime.Shutdown();
        }
 public ScriptScope CreateScope()
 {
     return(_scriptingRuntime.CreateScope());
 }
Пример #23
0
        internal static void InitialiseScriptingEnvironment()
        {
            ScriptRuntimeSetup Setup = new ScriptRuntimeSetup();

            Setup.LanguageSetups.Add(IronRuby.Ruby.CreateRubySetup());
            Setup.LanguageSetups.Add(IronPython.Hosting.Python.CreateLanguageSetup(null));
            RunTime = new ScriptRuntime(Setup);
            Engine  = RunTime.GetEngine("py");
            Scope   = RunTime.CreateScope();

            RunTime.IO.SetOutput(ShellOutStream, Encoding.UTF8);
            RunTime.IO.SetErrorOutput(ShellOutStream, Encoding.UTF8);

            Assembly MainAssembly = Assembly.GetExecutingAssembly();
            string   RootDir      = Directory.GetParent(MainAssembly.Location).FullName;
            string   HAGPath      = Path.Combine(RootDir, "HtmlAgilityPack.dll");
            Assembly HAGAssembly  = Assembly.LoadFile(HAGPath);

            RunTime.LoadAssembly(MainAssembly);
            RunTime.LoadAssembly(HAGAssembly);
            RunTime.LoadAssembly(typeof(String).Assembly);
            RunTime.LoadAssembly(typeof(Uri).Assembly);
            RunTime.LoadAssembly(typeof(XmlDocument).Assembly);

            Engine.Runtime.TryGetEngine("py", out Engine);
            List <string> PySearchPaths = new List <string>();

            foreach (string PyPath in PyPaths)
            {
                PySearchPaths.Add(PyPath.Replace("$ROOTDIR", RootDir));
            }
            try
            {
                Engine.SetSearchPaths(PySearchPaths);
            }
            catch (Exception Exp)
            {
                IronException.Report("Unable to set PyPaths", Exp.Message, Exp.StackTrace);
            }

            foreach (string PyCommand in PyCommands)
            {
                try
                {
                    ExecuteStartUpCommand(PyCommand);
                }
                catch (Exception Exp)
                {
                    IronException.Report("Unable to execute Python startup command - " + PyCommand, Exp.Message, Exp.StackTrace);
                }
            }

            Engine.Runtime.TryGetEngine("rb", out Engine);

            List <string> RbSearchPaths = new List <string>();

            foreach (string RbPath in RbPaths)
            {
                RbSearchPaths.Add(RbPath.Replace("$ROOTDIR", RootDir));
            }
            Engine.SetSearchPaths(RbSearchPaths);

            foreach (string RbCommand in RbCommands)
            {
                try
                {
                    ExecuteStartUpCommand(RbCommand);
                }
                catch (Exception Exp)
                {
                    IronException.Report("Unable to execute Ruby startup command" + RbCommand, Exp.Message, Exp.StackTrace);
                }
            }

            Engine.Runtime.TryGetEngine("py", out Engine);
            ExecuteStartUpCommand("print 123");
            ShellOutText = new StringBuilder();
            IronUI.ResetInteractiveShellResult();
        }