public PythonSingleLayer(PythonScriptHost host, string code, string name) { Name = name; Code = code; Host = host; string[] codeWithoutWhitespace = code.Split(new char[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries); string alltokens = ""; foreach (string token in codeWithoutWhitespace) { alltokens += token; } _id = alltokens.GetHashCode().ToString(); _scope = host.CreateScriptSource(code, name); if (_scope.ContainsVariable(_processannotations)) { _processAnnotationsFunc = _scope.GetVariable(_processannotations); } if (_scope.ContainsVariable(_interpret)) { _interpretFunc = _scope.GetVariable(_interpret); } }
/// <summary> /// Class constructor /// </summary> public IronPythonCompletionProvider() { _engine = Python.CreateEngine(); _scope = _engine.CreateScope(); VariableTypes = new Dictionary<string, Type>(); ImportedTypes = new Dictionary<string, Type>(); RegexToType.Add(singleQuoteStringRegex, typeof(string)); RegexToType.Add(doubleQuoteStringRegex, typeof(string)); RegexToType.Add(doubleRegex, typeof(double)); RegexToType.Add(intRegex, typeof(int)); RegexToType.Add(arrayRegex, typeof(List)); RegexToType.Add(dictRegex, typeof(PythonDictionary)); var assemblies = AppDomain.CurrentDomain.GetAssemblies(); if (assemblies.Any(x => x.FullName.Contains("RevitAPI")) && assemblies.Any(x => x.FullName.Contains("RevitAPIUI"))) { try { _scope.Engine.CreateScriptSourceFromString("import clr\n", SourceCodeKind.Statements).Execute(_scope); var revitImports = "clr.AddReference('RevitAPI')\nclr.AddReference('RevitAPIUI')\nfrom Autodesk.Revit.DB import *\nimport Autodesk\n"; _scope.Engine.CreateScriptSourceFromString(revitImports, SourceCodeKind.Statements).Execute(_scope); } catch { DynamoLogger.Instance.Log("Failed to load Revit types for autocomplete. Python autocomplete will not see Autodesk namespace types."); } } if (!assemblies.Any(x => x.FullName.Contains("LibGNet"))) { AssemblyHelper.LoadLibG(); //refresh the assemblies collection assemblies = AppDomain.CurrentDomain.GetAssemblies(); } if (assemblies.Any(x => x.FullName.Contains("LibGNet"))) { try { _scope.Engine.CreateScriptSourceFromString("import clr\n", SourceCodeKind.Statements).Execute(_scope); var libGImports = "import clr\nclr.AddReference('LibGNet')\nfrom Autodesk.LibG import *\n"; _scope.Engine.CreateScriptSourceFromString(libGImports, SourceCodeKind.Statements).Execute(_scope); } catch (Exception e) { DynamoLogger.Instance.Log(e.ToString()); DynamoLogger.Instance.Log("Failed to load LibG types for autocomplete. Python autocomplete will not see Autodesk namespace types."); } } }
public override void Execute(ScriptEngine engine, ScriptScope scope) { if (!string.IsNullOrEmpty(Path)) { engine.ExecuteFile(Path, scope); } }
public PythonScriptReader() { _engine = Python.CreateEngine(); _escope = _engine.CreateScope(); var reader = new StreamReader(new FileStream(@"Scripts\Script.py", FileMode.Open, FileAccess.Read)); string scriptText = reader.ReadToEnd(); reader.Close(); _engine.Execute(scriptText, _escope); if (!_escope.TryGetVariable("GeneratorFunc", out _randomGenerator)) { MessageBox.Show("Error Occurred in Executing python script! - GeneratorFunc", "Error"); throw new Exception("Error Occurred in Executing python script!"); } if (!_escope.TryGetVariable("userDefinedFunc", out _userDefinedMethod)) { MessageBox.Show("Error Occurred in Executing python script! - userDefinedFunc", "Error"); throw new Exception("Error Occurred in Executing python script!"); } if (!_escope.TryGetVariable("LifeSpanMapper", out _lifeTimeMapper)) { MessageBox.Show("Error Occurred in Executing python script! - LifeSpanMapper", "Error"); throw new Exception("Error Occurred in Executing python script!"); } if (!_escope.TryGetVariable("DelayMapper", out _delayTimeMapper)) { MessageBox.Show("Error Occurred in Executing python script! - DelayMapper", "Error"); throw new Exception("Error Occurred in Executing python script!"); } }
/// <summary> /// Publish objects so that the host can use it, and then block indefinitely (until the input stream is open). /// /// Note that we should publish only one object, and then have other objects be accessible from it. Publishing /// multiple objects can cause problems if the client does a call like "remoteProxy1(remoteProxy2)" as remoting /// will not be able to know if the server object for both the proxies is on the same server. /// </summary> /// <param name="remoteRuntimeChannelName">The IPC channel that the remote console expects to use to communicate with the ScriptEngine</param> /// <param name="scope">A intialized ScriptScope that is ready to start processing script commands</param> internal static void StartServer(string remoteRuntimeChannelName, ScriptScope scope) { Debug.Assert(ChannelServices.GetChannel(remoteRuntimeChannelName) == null); IpcChannel channel = CreateChannel("ipc", remoteRuntimeChannelName); LifetimeServices.LeaseTime = GetSevenDays(); LifetimeServices.LeaseManagerPollTime = GetSevenDays(); LifetimeServices.RenewOnCallTime = GetSevenDays(); LifetimeServices.SponsorshipTimeout = GetSevenDays(); ChannelServices.RegisterChannel(channel, false); try { RemoteCommandDispatcher remoteCommandDispatcher = new RemoteCommandDispatcher(scope); RemotingServices.Marshal(remoteCommandDispatcher, CommandDispatcherUri); // Let the remote console know that the startup output (if any) is complete. We use this instead of // a named event as we want all the startup output to reach the remote console before it proceeds. Console.WriteLine(RemoteCommandDispatcher.OutputCompleteMarker); // Block on Console.In. This is used to determine when the host process exits, since ReadLine will return null then. string input = System.Console.ReadLine(); Debug.Assert(input == null); } finally { ChannelServices.UnregisterChannel(channel); } }
public object Execute(CompiledCode compiledCode, ScriptScope scope) { Debug.Assert(_executingThread == null); _executingThread = Thread.CurrentThread; try { object result = compiledCode.Execute(scope); Console.WriteLine(RemoteCommandDispatcher.OutputCompleteMarker); return result; } catch (ThreadAbortException tae) { KeyboardInterruptException pki = tae.ExceptionState as KeyboardInterruptException; if (pki != null) { // Most exceptions get propagated back to the client. However, ThreadAbortException is handled // differently by the remoting infrastructure, and gets wrapped in a RemotingException // ("An error occurred while processing the request on the server"). So we filter it out // and raise the KeyboardInterruptException Thread.ResetAbort(); throw pki; } else { throw; } } finally { _executingThread = null; } }
public PythonLanguage() { _scope = Python.CreateEngine().CreateScope(); _scope.Engine.Runtime.LoadAssembly(typeof(string).Assembly); _scope.Engine.Runtime.LoadAssembly(typeof(Uri).Assembly); _scope.Engine.Runtime.LoadAssembly(typeof(SPList).Assembly); }
/// <summary> /// 初始化解释器 /// </summary> public void InitialzeInterpreter() { pythonEngine = Python.CreateEngine(); pythonScope = pythonEngine.CreateScope(); string initialString = @" import clr, sys import System.Collections.Generic.List as List clr.AddReference('Clover') from Clover import * # 获取CloverController的实例 clover = CloverController.GetInstance(); # 取出所有的函数指针 FindFacesByVertex = clover.FindFacesByVertex GetVertex = clover.GetVertex CutFaces = clover.AnimatedCutFaces _CutFaces = clover.CutFaces _RotateFaces = clover.RotateFaces RotateFaces = clover.AnimatedRotateFaces Undo = clover.Undo Redo = clover.Redo "; pythonEngine.Execute(initialString, pythonScope); }
public Engine() { Dictionary<String,Object> options = new Dictionary<string,object>(); options["DivisionOptions"] = PythonDivisionOptions.New; engine = Python.CreateEngine(options); scope = engine.CreateScope(); }
public override void Execute(ScriptEngine engine, ScriptScope scope) { if (!string.IsNullOrEmpty(Expression)) { engine.Execute(Expression, scope); } }
/// <summary> /// Load the core module that offers access to the simulation environment. /// </summary> public void LoadCoreModule() { scope = engine.CreateScope(); // Allow scriptable access to... scope.SetVariable("status", Program.form.toolStripStatus); // Statusbar. scope.SetVariable("log", Program.form.txtLog); // Simulation log. try { e_script = engine.CreateScriptSourceFromFile("syeon.py"); e_script.Execute(scope); } catch(Exception e) { DialogResult ans = MessageBox.Show( e.Message, SSE, MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error); if(ans == DialogResult.Abort) { Program.form.Close(); } else if(ans == DialogResult.Retry) { LoadCoreModule(); // Recursion rules! } } }
public RubyHelper() { Scope = Engine.CreateScope(); Engine.SetSearchPaths LoadRubyFiles(); }
public static void SendMethodToModules(string methodName, ScriptScope scope) { var engine = scope.Engine; var snippet = String.Format(RecompileSnippet, methodName); var source = engine.CreateScriptSourceFromString(snippet, SourceCodeKind.Statements); source.Execute(scope); }
public EditorDocument(string input = "") { if (input == "") { Title = "Untitled"; SavedBefore = false; } else { Title = Path.GetFileName(input); SavedBefore = true; InputFile = input; } _ruby = Settings.RubyTemplate; _scope = Settings.ScopeTemplate; var editor = Settings.ScintillaTemplate; if (input != "") editor.Text = File.ReadAllText(input); Content = new WindowsFormsHost { Child = editor }; }
/// <summary> /// Initializes a new instance of the <see cref="Distribox.CommonLib.RubyEngine"/> class. /// </summary> public RubyEngine() { this.scope = this.engine.CreateScope(); // warm up this.DoString("0"); }
/// <summary> /// Main method /// </summary> /// <param name="args">Command line args.</param> public static void Main(string[] args) { engine = Python.CreateEngine(); scope = engine.CreateScope(); engine.Runtime.LoadAssembly(typeof(TurntableBot).Assembly); engine.Runtime.LoadAssembly(typeof(JObject).Assembly); engine.Runtime.IO.RedirectToConsole(); ScriptSource source = null; if (File.Exists(Script)) { source = engine.CreateScriptSourceFromFile(Script); } else { Console.WriteLine("File not found"); } if (source != null) { try { source.Execute(scope); } catch (Exception e) { ExceptionOperations ops = engine.GetService<ExceptionOperations>(); Console.WriteLine(ops.FormatException(e)); } } Console.ReadLine(); }
/// <summary> /// Creates instances of the Ruby engine and Ruby scope /// </summary> public static void CreateRuntime() { _rubyRuntime = IronRuby.Ruby.CreateRuntime(); _rubyEngine = IronRuby.Ruby.GetEngine(_rubyRuntime); _rubyScope = _rubyEngine.CreateScope(); _rubyEngine.Execute(@"load_assembly 'IronRuby.Libraries', 'IronRuby.StandardLibrary.Zlib'", _rubyScope); }
public override void Load(string code = "") { Engine = IronPython.Hosting.Python.CreateEngine(); Scope = Engine.CreateScope(); Scope.SetVariable("Commands", chatCommands); Scope.SetVariable("DataStore", DataStore.GetInstance()); Scope.SetVariable("Find", Find.GetInstance()); Scope.SetVariable("GlobalData", GlobalData); Scope.SetVariable("Plugin", this); Scope.SetVariable("Server", Pluton.Server.GetInstance()); Scope.SetVariable("ServerConsoleCommands", consoleCommands); Scope.SetVariable("Util", Util.GetInstance()); Scope.SetVariable("Web", Web.GetInstance()); Scope.SetVariable("World", World.GetInstance()); try { Engine.Execute(code, Scope); Class = Engine.Operations.Invoke(Scope.GetVariable(Name)); Globals = Engine.Operations.GetMemberNames(Class); object author = GetGlobalObject("__author__"); object about = GetGlobalObject("__about__"); object version = GetGlobalObject("__version__"); Author = author == null ? "" : author.ToString(); About = about == null ? "" : about.ToString(); Version = version == null ? "" : version.ToString(); State = PluginState.Loaded; } catch (Exception ex) { Logger.LogException(ex); State = PluginState.FailedToLoad; } PluginLoader.GetInstance().OnPluginLoaded(this); }
public PyMovingAverage() { HandlePythonExceptions(() => { _engine = Python.CreateEngine(); var runtime = _engine.Runtime; foreach (var reference in GetReferences()) runtime.LoadAssembly(reference); string code = @" import sys sys.path.append(r'{0}') from MovingAverage import MovingAverage expert = MovingAverage() "; code = string.Format(code, GetBasePath()); _scope = _engine.CreateScope(); var source = _engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements); source.Execute(_scope); _expert = _scope.GetVariable("expert"); return 0; }); }
public PyInterpretUtility() { _engine = Python.CreateEngine(); _stdout = new MemoryStream(); _engine.Runtime.IO.SetOutput(_stdout, Encoding.ASCII); _scope = null; }
public PythonTF() { engine = Python.CreateEngine(); scope = engine.CreateScope(); Script = "value"; ScriptWorkMode = ScriptWorkMode.不进行转换; }
public Engine() { var options = new Dictionary<string, object>(); options["DivisionOptions"] = PythonDivisionOptions.New; _history = new NullStream(); _output = new EventRaisingStreamWriter(_history); _output.StringWritten += _output_StringWritten; _engine = Python.CreateEngine(options); _engine.Runtime.IO.SetOutput(_history, _output); _engine.Runtime.IO.SetErrorOutput(_history, _output); _scope = _engine.CreateScope(); foreach (var t in _pluggable) { _scope.SetVariable(t.Name, DynamicHelpers.GetPythonTypeFromType(t)); } _scope.SetVariable("CalculatorFunctions", DynamicHelpers.GetPythonTypeFromType(typeof(CalculatorFunctions))); _functioncache = new Dictionary<string, string>(); //hidden functions _functioncache.Add("Var", "CalculatorFunctions.Var"); _functioncache.Add("FncList", "CalculatorFunctions.FncList"); _functioncache.Add("RegFunction", "CalculatorFunctions.RegFunction"); foreach (var f in _functions) { if (_functioncache.ContainsKey(f.Name)) continue; _functioncache.Add(f.Name, f.FullName); } LoadBitops(); }
/// <summary> /// Class constructor /// </summary> public IronPythonCompletionProvider() { _engine = Python.CreateEngine(); _scope = _engine.CreateScope(); VariableTypes = new Dictionary<string, Type>(); ImportedTypes = new Dictionary<string, Type>(); RegexToType.Add(singleQuoteStringRegex, typeof(string)); RegexToType.Add(doubleQuoteStringRegex, typeof(string)); RegexToType.Add(doubleRegex, typeof(double)); RegexToType.Add(intRegex, typeof(int)); RegexToType.Add(arrayRegex, typeof(List)); RegexToType.Add(dictRegex, typeof(PythonDictionary)); try { _scope.Engine.CreateScriptSourceFromString("import clr\n", SourceCodeKind.Statements).Execute(_scope); var revitImports = "clr.AddReference('RevitAPI')\nclr.AddReference('RevitAPIUI')\nfrom Autodesk.Revit.DB import *\nimport Autodesk\n"; _scope.Engine.CreateScriptSourceFromString(revitImports, SourceCodeKind.Statements).Execute(_scope); } catch { DynamoLogger.Instance.Log("Failed to load Revit types for autocomplete. Python autocomplete will not see Autodesk namespace types."); } }
private void RenderView(ScriptScope scope, ViewContext context, TextWriter writer) { scope.SetVariable("view_data", context.ViewData); scope.SetVariable("model", context.ViewData.Model); scope.SetVariable("context", context); scope.SetVariable("response", context.HttpContext.Response); scope.SetVariable("url", new RubyUrlHelper(context.RequestContext)); scope.SetVariable("html", new RubyHtmlHelper(context, new Container(context.ViewData))); scope.SetVariable("ajax", new RubyAjaxHelper(context, new Container(context.ViewData))); var script = new StringBuilder(); Template.ToScript("render_page", script); if (_master != null) _master.Template.ToScript("render_layout", script); else script.AppendLine("def render_layout; yield; end"); script.AppendLine("def view_data.method_missing(methodname); get_Item(methodname.to_s); end"); script.AppendLine("render_layout { |content| render_page }"); try { _rubyEngine.ExecuteScript(script.ToString(), scope); } catch (Exception e) { writer.Write(e.ToString()); } }
public RubyInstaller(string fileName, List<Assembly> assemblies) { this.fileName = fileName; assemblies.AddRange(new[] { typeof(IServiceLocator).Assembly, typeof(IConvention).Assembly }); if(engine == null) { lock(@lock) { if(engine == null) { engine = IronRuby.Ruby.CreateEngine(); scope = engine.CreateScope(); assemblies.ForEach(a => engine.Runtime.LoadAssembly(a)); LoadResource("Siege.ServiceLocator.Dynamic.Scripts.Installer.rb"); LoadResource("Siege.ServiceLocator.Dynamic.Scripts.SiegeDSL.rb"); LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RubyRegistration.rb"); LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.RegistrationHandlerFactory.rb"); LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.DefaultRegistrationHandler.rb"); LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.DefaultInstanceRegistrationHandler.rb"); LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.ConditionalRegistrationHandler.rb"); LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.ConditionalInstanceRegistrationHandler.rb"); LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.NamedRegistrationHandler.rb"); LoadResource("Siege.ServiceLocator.Dynamic.Scripts.RegistrationHandlers.NamedInstanceRegistrationHandler.rb"); } } } this.source = engine.CreateScriptSourceFromFile(this.fileName); }
public Plugin(string filename) { this.filename = filename; scope = engine.CreateScope(); scope.SetVariable("hookme", Program.data.pluginMngr.pluginsApi); engine.SetSearchPaths(Program.data.configuration.lstPluginsSearchPath); }
public void Run(ScriptScope scope) { if (scope == ScriptScope.CurrentFile) RunFile(); else if (scope == ScriptScope.AllOpenFiles) RunAllFiles(); }
public Ruby() { //Setup the script engine runtime var setup = new ScriptRuntimeSetup(); setup.LanguageSetups.Add( new LanguageSetup( "IronRuby.Runtime.RubyContext, IronRuby", "IronRuby 1.0", new[] { "IronRuby", "Ruby", "rb" }, new[] { ".rb" })); setup.DebugMode = true; //Create the runtime, engine, and scope runtime = ScriptRuntime.CreateRemote(AppDomain.CurrentDomain, setup); engine = runtime.GetEngine("Ruby"); scope = engine.CreateScope(); try { engine.Execute(@"$RGSS_VERSION = " + Program.GetRuntime().GetRGSSVersion(), scope); engine.Execute(@"$GAME_DIRECTORY = '" + Program.GetRuntime().GetResourcePaths()[0].Replace(@"\", @"\\") + @"'", scope); engine.Execute(@"$GAME_OS_WIN = " + Program.GetRuntime().IsWindowsOS().ToString().ToLower(), scope); } catch (Exception e) { Program.Error(e.Message); } //Load system internals and our Ruby internals Console.WriteLine("Loading system"); //engine.Execute(System.Text.Encoding.UTF8.GetString(Properties.Resources.System), scope); string script = System.Text.Encoding.UTF8.GetString(Properties.Resources.System); script = script.Substring(1); //fix for a weird character that shouldn't be there o.O Eval(script); //Load the adaptable RPG datatypes script = System.Text.Encoding.UTF8.GetString(Properties.Resources.RPG); script = script.Substring(1); Eval(script); //Load the version appropriate RPG datatypes if (Program.GetRuntime().GetRGSSVersion() == 1) { script = System.Text.Encoding.UTF8.GetString(Properties.Resources.RPG1); script = script.Substring(1); Eval(script); } if (Program.GetRuntime().GetRGSSVersion() == 2) { script = System.Text.Encoding.UTF8.GetString(Properties.Resources.RPG2); script = script.Substring(1); Eval(script); } if (Program.GetRuntime().GetRGSSVersion() == 3) { script = System.Text.Encoding.UTF8.GetString(Properties.Resources.RPG3); script = script.Substring(1); Eval(script); } }
public ScriptHost() { m_engine = Python.CreateEngine(); m_scope = m_engine.CreateScope(); CreateOutputBuffer(); }
private static void Main() { try { PyEngine = Python.CreateEngine(); NtrClient = new NtrClient(); ScriptHelper = new ScriptHelper(); GlobalScope = PyEngine.CreateScope(); GlobalScope.SetVariable("nc", ScriptHelper); LoadConfig(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); GCmdWindow = new CmdWindow(); Dc = new DebugConsole(); Application.Run(GCmdWindow); } catch (Exception e) { BugReporter br = new BugReporter(e, "Program exception"); MessageBox.Show( @"WARNING - NTRDebugger has encountered an error" + Environment.NewLine + @"This error is about to crash the program, please send the generated" + Environment.NewLine + @"Error log to imthe666st!" + Environment.NewLine + Environment.NewLine + @"Sorry for the inconvinience -imthe666st" ); } }
/// <summary> /// Ctor. /// </summary> public PythonInterpreter() { this.scope = this.engine.CreateScope(); this.scope.SetVariable("Objects", new ObjectUtils.Objects()); this.scope.SetVariable("Heap", new ObjectUtils.Heap()); }
public InterpretedMethod(ClassMethodDeclarationExpression expression, ScriptScope script_scope) { _expression = expression; _script_scope = script_scope; }
public RemoteConsoleCommandLine(ScriptScope scope, RemoteCommandDispatcher remoteCommandDispatcher, AutoResetEvent remoteOutputReceived) { _remoteConsoleCommandDispatcher = new RemoteConsoleCommandDispatcher(remoteCommandDispatcher, remoteOutputReceived); Debug.Assert(scope != null); ScriptScope = scope; }
internal T Execute <T>(ScriptScope scope) { return(_code.Execute <T>(scope)); }