Exemplo n.º 1
0
        public static void PassingVariablesToCompiledCode(
            string question, object correctResponse)
        {
            var runtimeSetup  = new ScriptRuntimeSetup();
            var languageSetup = new LanguageSetup(
                "IronPython.Runtime.PythonContext, IronPython",
                "IronPython", new[] { "Python" }, new[] { ".py" });

            runtimeSetup.LanguageSetups.Add(languageSetup);
            var          runtime = new ScriptRuntime(runtimeSetup);
            ScriptEngine engine  = runtime.GetEngine("Python");

            ScriptSource source =
                engine.CreateScriptSourceFromString(@"
import Question
import CorrectResponse
input(Question) == CorrectResponse
");

            CompiledCode AskQuestion = source.Compile();

            runtime.Globals.SetVariable("Question", question);
            runtime.Globals.SetVariable(
                "CorrectResponse", correctResponse);

            Console.WriteLine("You chose... {0}",
                              AskQuestion.Execute <bool>()
          ? "wisely."
          : "poorly");
        }
Exemplo n.º 2
0
 public Engine()
 {
     // Load a script with all the utility functions that are required
     // pe.ExecuteFile(InputTestDirectory + "\\EngineTests.py");
     _env = Python.CreateRuntime();
     _pe  = _env.GetEngine("py");
 }
Exemplo n.º 3
0
        public static void MultiLanguageLoad()
        {
            var runtimeSetup = new ScriptRuntimeSetup();
            var pythonSetup  = new LanguageSetup(
                typeName: "IronPython.Runtime.PythonContext, IronPython",
                displayName: "IronPython",
                names: new[] { "IronPython", "Python", "py" },
                fileExtensions: new[] { ".py" });

            runtimeSetup.LanguageSetups.Add(pythonSetup);
            var rubySetup = new LanguageSetup(
                typeName: "IronRuby.Runtime.RubyContext, IronRuby",
                displayName: "IronRuby",
                names: new[] { "IronRuby", "Ruby", "rb" },
                fileExtensions: new[] { ".rb" });

            runtimeSetup.LanguageSetups.Add(rubySetup);
            ScriptRuntime runtimeObject =
                new ScriptRuntime(runtimeSetup);
            ScriptEngine pythonEngine =
                runtimeObject.GetEngine("Python");
            ScriptEngine rubyEngine =
                runtimeObject.GetEngineByFileExtension(".rb");

            pythonEngine.Execute("print 'Hello from Python!'");
            rubyEngine.Execute("puts 'Hello from Ruby!'");
        }
        static public void Run(string filePath)
        {
            // Setup DLR ScriptRuntime with our languages.  We hardcode them here
            // but a .NET app looking for general language scripting would use
            // an app.config file and ScriptRuntime.CreateFromConfiguration.
            var    setup         = new ScriptRuntimeSetup();
            string qualifiedname = typeof(VBScriptContext).AssemblyQualifiedName;

            setup.LanguageSetups.Add(new LanguageSetup(
                                         qualifiedname, "vbscript", new[] { "vbscript" }, new[] { ".vbs" }));
            var dlrRuntime = new ScriptRuntime(setup);

            //Add the VBScript runtime assembly
            dlrRuntime.LoadAssembly(typeof(global::Dlrsoft.VBScript.Runtime.BuiltInFunctions).Assembly);

            // Get a VBScript engine and run stuff ...
            var engine       = dlrRuntime.GetEngine("vbscript");
            var scriptSource = engine.CreateScriptSourceFromFile(filePath);
            var compiledCode = scriptSource.Compile();
            var feo          = engine.CreateScope();

            //feo = engine.ExecuteFile(filename, feo);
            feo.SetVariable("Assert", new NunitAssert());
            compiledCode.Execute(feo);
        }
Exemplo n.º 5
0
        public static void Scenario_RemoteEvaluation()
        {
            ScriptRuntime runtime = ScriptRuntime.CreateRemote(
                AppDomain.CreateDomain("remote domain"),
                ScriptRuntimeSetup.ReadConfiguration()
                );

            ScriptEngine     engine = runtime.GetEngine("python");
            ObjectOperations ops    = engine.Operations;

            ObjectHandle classC = engine.ExecuteAndWrap(@"
class C(object):
  def __init__(self, value):
    self.value = value
    
  def __int__(self):
    return self.value

C
");

            ObjectHandle result    = ops.CreateInstance(classC, 17);
            int          intResult = ops.Unwrap <int>(result);

            Console.WriteLine(intResult);
        }
Exemplo n.º 6
0
        public void run()
        {
            if (HelpRequested || errors.Count > 0)
            {
                foreach (var error in errors)
                {
                    Console.WriteLine(error);
                }
                provideHelp();
                return;
            }
            ScriptRuntime scriptRuntime = null;

            try {
                // ScriptRuntime scriptRuntime = ScriptRuntime.CreateFromConfiguration();  // This is the "standard" way to do it; but it's rather less flexible.
                scriptRuntime = EssenceLaunchPad.CreateRuntime(optionsBuilder);
                ScriptEngine engine = scriptRuntime.GetEngine("Essence#");
                foreach (var executive in executives)
                {
                    executive.run(engine);
                }
            } finally {
                if (scriptRuntime != null)
                {
                    scriptRuntime.Shutdown();
                }
            }
        }
Exemplo n.º 7
0
        public AspHost(AspHostConfiguration config)
        {
            _config = config;

            ScriptRuntimeSetup setup = new ScriptRuntimeSetup();

            if (config != null && config.Trace)
            {
                setup.Options["Trace"] = ScriptingRuntimeHelpers.True;
            }

            string qualifiedname = typeof(VBScriptContext).AssemblyQualifiedName;

            setup.LanguageSetups.Add(new LanguageSetup(
                                         qualifiedname, "vbscript", new[] { "vbscript" }, new[] { ".vbs" }));
            _runtime = new ScriptRuntime(setup);
            if (config != null && config.Assemblies != null)
            {
                foreach (Assembly a in config.Assemblies)
                {
                    _runtime.LoadAssembly(a);
                }
            }
            _engine = _runtime.GetEngine("vbscript");
        }
Exemplo n.º 8
0
        public void TestIssue1()
        {
            var qs = qsrt.GetEngine("Qs");

            // tell qs evaluator that we have external place for variables

            Qs.Runtime.QsEvaluator.CurrentEvaluator.Scope.RegisterScopeStorage("CircleStorage", new CircleStorage());

            var ev = Qs.Runtime.QsEvaluator.CurrentEvaluator;

            DimensionlessQuantity <double> g = 34.2;
            DimensionlessQuantity <string> h = "hello there";

            dynamic r = qs.Execute("_circle->Particles[10]->M");

            //qs.Execute("_c[55]=20");
            qs.Execute("_c->Tag =\"hello\"");

            qs.Execute("_c->RedCircle->Tag=\"hello\"");

            qs.Execute("_c->RedCircle->Particles[20]->M=30");

            var ms = (QsScalar)ev.Evaluate("_c->RedCircle->Particles[20]->M");

            Assert.AreEqual(ms.NumericalQuantity.Value, 30);



            qs.Execute("_c->RedCircle[10]=20");
            var s = (QsScalar)ev.Evaluate("_c->RedCircle[10]");

            Assert.AreEqual(s.NumericalQuantity.Value, 20);
        }
Exemplo n.º 9
0
        public void GetScalarTest()
        {
            ScriptRuntime qsruntime = Qs.Scripting.QsContext.CreateRuntime();
            ScriptEngine  QsEngine  = qsruntime.GetEngine("Qs");

            QsTensor t = QsEngine.Execute("<|3 4; 3 1 | 9 8; 4 7  |>") as QsTensor;


            var sv = t.GetScalar(0, 0, 0);

            Assert.AreEqual("3<1>", sv.ToShortString());


            t = QsEngine.Execute("<| <|3 4; 3 1 | 9 8; 4 7|> | <|30 4; 3 1 | 9 18; 4 7|> |>") as QsTensor;

            // getting scalar from 4th rank tensor.
            sv = t.GetScalar(1, 1, 0, 1);

            Assert.AreEqual("18<1>", sv.ToShortString());


            t = QsEngine.Execute("<| <| <|3 4; 3 1 | 9 8; 4 7|> | <|30 4; 3 1 | 9 18; 4 7|> |>  |  <| <|3 4;4 1 | 9 8; 4 7|> | <|30 403<L>; 302 1 | 19 180; 40 700|> |> |>") as QsTensor;

            // getting scalar from 5th rank tensor.
            sv = t.GetScalar(1, 1, 0, 0, 1);

            Assert.AreEqual("403<L>", sv.ToShortString());
        }
Exemplo n.º 10
0
        public ScriptManager(string scriptsDir, string pythonLibsDir)
        {
            _scripts = new Dictionary <string, Script>();

            ScriptRuntime runtime = Python.CreateRuntime();

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                runtime.LoadAssembly(assembly);
            }

            _scriptEngine = runtime.GetEngine("py");
            var paths = _scriptEngine.GetSearchPaths();

            if (!string.IsNullOrEmpty(scriptsDir))
            {
                paths.Add(scriptsDir);
            }

            if (!string.IsNullOrEmpty(pythonLibsDir))
            {
                paths.Add(pythonLibsDir);
            }

            _scriptEngine.SetSearchPaths(paths);
        }
Exemplo n.º 11
0
        public void GetRegisteredExtensions_LangWithNoExt()
        {
            ScriptRuntime runtime = ScriptRuntimeTest.CreatePythonOnlyRuntime(new string[] { "py" }, new string[] { });
            ScriptEngine  engine  = runtime.GetEngine("py");

            Assert.IsTrue(0 == engine.Setup.FileExtensions.Count);
        }
Exemplo n.º 12
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object can be used to retrieve data from input parameters and
        /// to store data in output parameters.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var path         = @"C:\Users\darthoma\Documents\GitHub\honey-badger\examples\helloworld\helloworld.py";
            var runtimeSetup = Python.CreateRuntimeSetup((IDictionary <string, object>)null);

            runtimeSetup.Options.Add("DivisionOptions", (object)PythonDivisionOptions.New);
            runtimeSetup.Options.Add("Frames", (object)true);
            runtimeSetup.Options.Add("Tracing", (object)true);
            ScriptRuntime scriptRuntime = new ScriptRuntime(runtimeSetup);

            scriptRuntime.LoadAssembly(typeof(RhinoApp).Assembly);
            scriptRuntime.LoadAssembly(typeof(int).Assembly);
            scriptRuntime.LoadAssembly(typeof(Form).Assembly);
            scriptRuntime.LoadAssembly(typeof(Color).Assembly);
            scriptRuntime.LoadAssembly(typeof(LengthExtension).Assembly);

            var engine = scriptRuntime.GetEngine("py");
            var stream = new hbtestStdioStream();

            scriptRuntime.IO.SetErrorOutput((Stream)stream, Encoding.Default);
            scriptRuntime.IO.SetOutput((Stream)stream, Encoding.Default);
            scriptRuntime.IO.SetInput((Stream)stream, Encoding.Default);

            ScriptScope  scope = engine.CreateScope();
            ScriptSource scriptSourceFromFile = engine.CreateScriptSourceFromFile(
                path, Encoding.Default, SourceCodeKind.Statements);

            scriptSourceFromFile.Execute(scope);

            var main   = scope.GetVariable("main");
            var result = main("hello, world");

            RhinoApp.WriteLine($"executed: {result}");
        }
Exemplo n.º 13
0
        internal Host(LanguageSetup language, string languageName, bool enableDebug)
        {
            _output = new MemoryStream();
            _error  = new MemoryStream();

            //var configFile = Path.GetFullPath(Uri.UnescapeDataString(new Uri(typeof(Host).Assembly.CodeBase).AbsolutePath)) + ".config";
            //_runtime = new ScriptRuntime(ScriptRuntimeSetup.ReadConfiguration(configFile));

            ScriptRuntimeSetup setup = new ScriptRuntimeSetup();

            if (enableDebug)
            {
                language.Options["Debug"] = Microsoft.Scripting.Runtime.ScriptingRuntimeHelpers.True;
                setup.DebugMode           = true;
            }
            setup.LanguageSetups.Add(language);

            _runtime = new ScriptRuntime(setup);
            _engine  = _runtime.GetEngine(languageName);

            _runtime.IO.SetOutput(_output, new StreamWriter(_output));
            _runtime.IO.SetErrorOutput(_error, new StreamWriter(_error));

            _theScope = _engine.CreateScope();
            _theScope.SetVariable("_host", this);
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            // Setup DLR ScriptRuntime with our languages.  We hardcode them here
            // but a .NET app looking for general language scripting would use
            // an app.config file and ScriptRuntime.CreateFromConfiguration.
            var    setup         = new ScriptRuntimeSetup();
            string qualifiedname = typeof(VBScriptContext).AssemblyQualifiedName;

            setup.LanguageSetups.Add(new LanguageSetup(
                                         qualifiedname, "vbscript", new[] { "vbscript" }, new[] { ".vbs" }));
            var dlrRuntime = new ScriptRuntime(setup);

            // Don't need to tell the DLR about the assemblies we want to be
            // available, which the SymplLangContext constructor passes to the
            // Sympl constructor, because the DLR loads mscorlib and System by
            // default.
            //dlrRuntime.LoadAssembly(typeof(object).Assembly);
            dlrRuntime.LoadAssembly(typeof(global::Dlrsoft.VBScript.Runtime.BuiltInFunctions).Assembly);

            // Get a Sympl engine and run stuff ...
            var engine = dlrRuntime.GetEngine("vbscript");
            //string filename = @"..\..\test\test.vbs";
            string filename     = args[0];
            var    scriptSource = engine.CreateScriptSourceFromFile(filename);
            var    compiledCode = scriptSource.Compile();
            var    feo          = engine.CreateScope(); //File Level Expando Object

            //feo = engine.ExecuteFile(filename, feo);
            feo.SetVariable("response", System.Console.Out);
            compiledCode.Execute(feo);
            Console.WriteLine("Type any key to continue..");
            Console.Read();
        }
Exemplo n.º 15
0
 internal void SetLanguageAsIronPython()
 {
     try
     {
         Engine = RunTime.GetEngine("py");
         Directory.SetCurrentDirectory(Config.RootDir);
         PluginEditorTE.SetHighlighting("Python");
         PluginEditorTE.Refresh();
         CheckSyntax();
         CurrentLanguage = "py";
     }
     catch (Exception Exp)
     {
         IronUI.ShowPluginCompilerError("Error Changing Language: " + Exp.Message);
     }
 }
Exemplo n.º 16
0
        public PythonEngine(ContentManager content)
        {
            ScriptRuntime runtime = Python.CreateRuntime(new Dictionary <string, object>
            {
#if DEBUG
                { "Debug", true },
#endif
            });
            var interopClasses = new[]
            {
                typeof(BaseEntity),
                typeof(Microsoft.Xna.Framework.Graphics.Texture2D),
                typeof(Jv.Games.Xna.Sprites.Sprite),
            };

            foreach (var interopType in interopClasses)
            {
                runtime.LoadAssembly(Assembly.GetAssembly(interopType));
            }

            Engine = runtime.GetEngine("py");
            var paths = Engine.GetSearchPaths();

            paths.Add("PlayerScripts");
            paths.Add(Path.Combine(content.RootDirectory, "Scripts"));
            paths.Add(Path.Combine(content.RootDirectory, "Scripts/Entities"));
            Engine.SetSearchPaths(paths);
        }
Exemplo n.º 17
0
    static void Main()
    {
        var setup = new ScriptRuntimeSetup();

        setup.LanguageSetups.Add(
            new LanguageSetup(
                typeof(RubyContext).AssemblyQualifiedName,
                "IronRuby",
                new[] { "IronRuby" },
                new[] { ".rb" }
                )
            );
        var runtime = new ScriptRuntime(setup);
        var engine  = runtime.GetEngine("IronRuby");
        var ec      = Ruby.GetExecutionContext(runtime);

        ec.DefineGlobalVariable("bob", new Person
        {
            Name         = "Bob",
            Age          = 30,
            Weight       = 213,
            FavouriteDay = "1/1/2000"
        });
        var eval = engine.Execute <bool>(
            "return ($bob.Age && 3 && $bob.Weight > 50) || $bob.Age < 3"
            );

        Console.WriteLine(eval);
    }
Exemplo n.º 18
0
        /// <summary>
        /// ItemCF推荐
        /// 给用户id为user_id的用户推荐电影
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public static ArrayList recommendItemCF(int user_id)
        {
            string        serverpath = pyScriptPath + "ItemCFRecommend.py";
            ScriptRuntime pyRuntime  = Python.CreateRuntime();
            ScriptEngine  Engine     = pyRuntime.GetEngine("python");

            ICollection <string> Paths = Engine.GetSearchPaths();

            Paths.Add("D:\\Anaconda2-32\\Lib");
            Paths.Add("D:\\Anaconda2-32\\DLLs");
            Paths.Add("D:\\Anaconda2-32\\Lib\\site-packages");

            Engine.SetSearchPaths(Paths);

            ScriptScope pyScope = Engine.CreateScope();

            dynamic pyScript = Engine.ExecuteFile(serverpath, pyScope);

            IronPython.Runtime.List user_item_list = getUserLikeItem(user_id);

            PythonDictionary similar_matrix = getItemSimilarityMatrix(user_item_list);


            IronPython.Runtime.List result = pyScript.recommend_item_cf(user_item_list, similar_matrix, 3);

            return(getRecommendMovie(result));
        }
Exemplo n.º 19
0
        //todo[lt3] doesn't work
        static void Main(string[] args)
        {
            //ScriptRuntime env = ScriptRuntime.CreateFromConfiguration();
            ScriptRuntimeSetup setup  = new ScriptRuntimeSetup();
            LanguageSetup      lsetup = new LanguageSetup(
                typeof(ClojureContext).AssemblyQualifiedName,
                ClojureContext.ClojureDisplayName,
                ClojureContext.ClojureNames.Split(new Char[] { ';' }),
                ClojureContext.ClojureFileExtensions.Split(new Char[] { ';' }));


            setup.LanguageSetups.Add(lsetup);
            ScriptRuntime env = new ScriptRuntime(setup);

            ScriptEngine curEngine = env.GetEngine("clj");

            Console.WriteLine("CurrentEngine: {0}", curEngine.LanguageVersion.ToString());
            ScriptScope scope = curEngine.CreateScope();

            Console.WriteLine("Scope: {0}", scope.GetItems());
            Console.WriteLine("REPL started, q for quit");
            var           argList = new List <string>(args);
            string        t       = "xx";
            Func <string> getCmd  = () =>
            {
                Console.Write("> ");
                if (argList.Count() > 0)
                {
                    var r = argList[0];
                    argList.RemoveAt(0); //lt2 rf Pull
                    return(r);
                }
                return(Console.ReadLine());
            };
            Func <string, object> execute_inner = (tt => scope.Engine.Execute(tt, scope));
            bool failSafe = false;

            while ((t = getCmd()) != "q")
            {
                object r;
                if (failSafe)
                {
                    try
                    {
                        r = (t == "" ? null : execute_inner(t));
                    }
                    catch (Exception ex)
                    {
                        r = ex;
                        throw; //xx
                    }
                }
                else
                {
                    r = execute_inner(t);
                }
                PrintResult(r);
            }
        }
Exemplo n.º 20
0
        public void ReadConfiguration_DuplicateEmptyExtensions()
        {
            LangSetup rb1 = new LangSetup(LangSetup.Ruby.Names, new[] { "", "" }, LangSetup.Ruby.DisplayName,
                                          LangSetup.Ruby.TypeName, LangSetup.Ruby.AssemblyString);

            LangSetup py2 = new LangSetup(LangSetup.Python.Names, new[] { "", "" }, LangSetup.Python.DisplayName,
                                          LangSetup.Python.TypeName, LangSetup.Python.AssemblyString);

            string configFile = GetTempConfigFile(new[] { rb1, py2 });
            var    srs        = ScriptRuntimeSetup.ReadConfiguration(configFile);

            var sr   = new ScriptRuntime(srs);
            var eng  = sr.GetEngine("py");
            var eng2 = sr.GetEngine("rb");

            Assert.AreEqual(5, eng.Execute("2+3"));
        }
Exemplo n.º 21
0
        public void LoadCommands()
        {
            Logger.Info("Loading commands.");

            Dictionary <string, ScriptCommand> newCommands = new Dictionary <string, ScriptCommand>(StringComparer.InvariantCultureIgnoreCase);

            foreach (CommandInfo info in CommandManager.GetItems())
            {
                if (newCommands.ContainsKey(info.Name))
                {
                    Logger.Warn("Duplicated command name '{0}' detected. Only the first will be loaded.", info.Name);
                    continue;
                }

                try
                {
                    if (!runtime.TryGetEngineByFileExtension(info.Language, out var engine))
                    {
                        engine = runtime.GetEngine(info.Language);
                    }

                    ScriptSource source = engine.CreateScriptSourceFromString(info.ScriptCode, Microsoft.Scripting.SourceCodeKind.Statements);
                    CompiledCode code   = source.Compile();
                    ScriptScope  scope  = engine.CreateScope();
                    scope.SetVariable("plugins", Plugins);

                    foreach (var param in info.Parameters)
                    {
                        scope.SetVariable(param.Name, null);
                    }

                    if (!string.IsNullOrEmpty(info.ScriptFile))
                    {
                        engine.ExecuteFile(info.ScriptFile, scope);
                    }

                    newCommands.Add(info.Name, new ScriptCommand(code, scope));
                    Logger.Debug("Added command '{0}'.", info.Name);
                }
                catch (Exception x)
                {
                    Logger.Error(x, "Error loading command '{0}'.", info.Name);
                }
            }
            commands = newCommands;
        }
Exemplo n.º 22
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();
        }
Exemplo n.º 23
0
        private static void Transformator(object context)
        {
            ThreadContext p = (ThreadContext)context;

            ScriptRuntime   runtime         = Python.CreateRuntime();
            ScriptEngine    engine          = runtime.GetEngine("py");
            LanguageContext languageContext = HostingHelpers.GetLanguageContext(engine);

            while (p.Running)
            {
                string pySrc;
                if (p.Queue.TryDequeue(out pySrc))
                {
                    LocalSink sink = new LocalSink();

                    try
                    {
                        SourceUnit src = HostingHelpers.GetSourceUnit(engine.CreateScriptSourceFromString(pySrc));

                        CompilerContext ctx    = new CompilerContext(src, languageContext.GetCompilerOptions(), sink);
                        Parser          parser = Parser.CreateParser(ctx, (PythonOptions)languageContext.Options);

                        PythonAst           ast       = parser.ParseFile(true);
                        JavascriptGenerator generator = new JavascriptGenerator(src, sink);

                        if (sink.IsError)
                        {
                            p.SetOutput(null);
                        }
                        else
                        {
                            p.SetOutput(generator.ToJavaScript(ast));
                        }
                    }
                    catch (Exception e)
                    {
                        if (!sink.IsError)
                        {
                            p.SetOutput(e.ToString());
                        }
                    }
                    finally
                    {
                        p.SetErrors(sink.Messages);
                    }
                }
                else
                {
                    Thread.Sleep(50);
                    if (p.Queue.Count == 0)
                    {
                        p.Suspend();
                    }
                }
            }
        }
Exemplo n.º 24
0
        public void Setup_InvalidTypeName()
        {
            // Dev10 bug 502234
            var setup = ScriptRuntimeTest.CreateSetup();

            setup.LanguageSetups[0].TypeName = setup.LanguageSetups[0].TypeName.Replace("PythonContext", "PythonBuffer");
            var runtime = new ScriptRuntime(setup);

            runtime.GetEngine("py");
        }
Exemplo n.º 25
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());
        }
Exemplo n.º 26
0
        private ScriptEngine CreateEngine()
        {
            var setup = new ScriptRuntimeSetup();

            setup.LanguageSetups.Add(Python.CreateLanguageSetup(null));
            setup.DebugMode = true;
            var runtime = new ScriptRuntime(setup);

            return(runtime.GetEngine("py"));
        }
Exemplo n.º 27
0
        protected void SaveCommand(CommandInfo item)
        {
            string ext = item.Language ?? ".py";

            if (!runtime.TryGetEngineByFileExtension(ext, out var engine))
            {
                engine = runtime.GetEngine(item.Language);
                ext    = engine.Setup.FileExtensions.First();
            }

            if (!ext.StartsWith("."))
            {
                ext = '.' + ext;
            }

            string path = Path.Combine(directory, Path.GetFileName(item.Name) + ext);

            using (var writer = File.CreateText(path))
            {
                var xmlSettings = new XmlWriterSettings()
                {
                    Indent             = true,
                    OmitXmlDeclaration = true
                };

                using (XmlWriter xml = XmlWriter.Create(new CommentWriter(writer), xmlSettings))
                {
                    xml.WriteStartElement("command");
                    xml.WriteElementString("description", item.Description);
                    foreach (var p in item.Parameters)
                    {
                        xml.WriteStartElement("param");
                        xml.WriteAttributeString("name", p.Name);
                        xml.WriteAttributeString("type", p.Type);
                        xml.WriteString(p.Description);
                        xml.WriteEndElement();
                    }
                    xml.WriteEndElement();

                    xml.Flush();
                }

                writer.WriteLine();
                writer.WriteLine();

                using (var reader = new StringReader(item.ScriptCode.TrimEnd()))
                {
                    string line;
                    while (null != (line = reader.ReadLine()))
                    {
                        writer.WriteLine(line);
                    }
                }
            }
        }
Exemplo n.º 28
0
        public override void Reset(ScriptScope scope)
        {
            var setup = new ScriptRuntimeSetup();
            var ls    = new LanguageSetup(typeof(PythonContext).AssemblyQualifiedName, "Python", new[] { "py" }, new[] { ".py" });

            setup.LanguageSetups.Add(ls);
            var runtime = new ScriptRuntime(setup);

            _engine = runtime.GetEngine("py");
            _scope  = scope == null?_engine.Runtime.CreateScope() : scope;
        }
        internal static bool IsValid(this ScriptRuntime sr)
        {
            ScriptEngine se = sr.GetEngine("py");
            ScriptScope  ss = se.CreateScope();

            ScriptSource code = se.CreateScriptSourceFromString("five=2+3", Microsoft.Scripting.SourceCodeKind.Statements);

            code.Execute(ss);

            return((int)ss.GetVariable("five") == 5);
        }
Exemplo n.º 30
0
        private static void initAsNeeded()
        {
            if (_runtime != null)
            {
                return;
            }

            BugFixer.Run();
            DebugUtil.Trigger();

            string langQName = typeof(IronPython.Runtime.PythonContext).AssemblyQualifiedName;
            var    langSetup = new LanguageSetup(langQName, "IronPython",
                                                 new string[] { "IronPython", "Python", "py" }, new string[] { ".py" });
            var setup = new ScriptRuntimeSetup();

            langSetup.ExceptionDetail = true;
            // options can be found in ironpython2-ipy-2.7.7\Languages\IronPython\IronPython\Runtime\PythonOptions.cs
            langSetup.Options["Optimize"]        = false;
            langSetup.Options["StripDocStrings"] = false;
            langSetup.Options["Frames"]          = true;
            langSetup.Options["Tracing"]         = true;
            //
            setup.LanguageSetups.Add(langSetup);
            //this is responsible for python being able to access private members on CLR objects:
            setup.PrivateBinding = true;

            _runtime = new ScriptRuntime(setup);
            _engine  = _runtime.GetEngine("IronPython");

            //This works for the simple purpose of creating a __main__ module
            //inspect.stack() should work after doing this.
            //Not sure if there's a better way.
            //This solution is from:
            //https://stackoverflow.com/questions/8264596/how-do-i-set-name-to-main-when-using-ironpython-hosted
            var pco = (IronPython.Compiler.PythonCompilerOptions)_engine.GetCompilerOptions();

            pco.ModuleName = "__main__";
            pco.Module    |= IronPython.Runtime.ModuleOptions.Initialize;
            var          source   = Engine.CreateScriptSourceFromString(@"'''This is the __main__ module'''");
            CompiledCode compiled = source.Compile(pco);

            mainScope = CreateScope();
            compiled.Execute(mainScope);

            //more options
            string[] searchpaths = new string[]
            {
                System.IO.Path.Combine(Util.ModBasePath, "IronPython-2.7.7/Lib/"),
                System.IO.Path.Combine(Util.ModBasePath, "PythonModules/")
            };
            _engine.SetSearchPaths(searchpaths);
            _runtime.LoadAssembly(System.Reflection.Assembly.GetExecutingAssembly());
            _runtime.LoadAssembly(typeof(Verse.Game).Assembly);
        }