// Update is called once per frame void Update() { scope = engine.CreateScope(); PreExec(); Exec(); PostExec(); }
public static void AddVariables(ScriptingHosting.ScriptScope scope, IEnumerable <KeyValuePair <string, object> > variables) { foreach (var kv in variables) { scope.SetVariable(kv.Key, kv.Value); } return; }
public static void AddPythonStandardLibrary(ScriptingHosting.ScriptScope scope) { var thisAssembly = typeof(ScriptUtil).Assembly; var pythonLibResourceName = thisAssembly.GetManifestResourceNames() .Single(name => name.ToLowerInvariant().EndsWith(PYTHON_LIB_ZIP_NAME.ToLowerInvariant())); var importer = new IronPython.Modules.ResourceMetaPathImporter(thisAssembly, pythonLibResourceName); dynamic sysModule = IronPython.Hosting.Python.GetSysModule(scope.Engine); sysModule.meta_path.append(importer); return; }
/// <summary> /// Creates new instance of IPy engine with given stream /// </summary> /// <param name="iostream">stream object to be used for I/O</param> /// <remarks></remarks> public IPyEngine(System.IO.Stream iostream, bool AddExecutingAssembly = true) { this.Engine = Python.CreateEngine(); Runtime = this.Engine.Runtime; EngineScope = this.Engine.CreateScope(); _io = iostream; SetStreams(_io); if (AddExecutingAssembly) { Runtime.LoadAssembly(Assembly.GetExecutingAssembly()); } }
/// <summary> /// Creates new instance of IPy engine with given stream /// </summary> /// <param name="iostream">stream object to be used for I/O</param> /// <remarks></remarks> public IPyEngine(System.IO.Stream iostream, bool AddExecutingAssembly = true) { this.Engine = Python.CreateEngine(); Runtime = this.Engine.Runtime; EngineScope = this.Engine.CreateScope(); _io = iostream; SetStreams(_io); if (AddExecutingAssembly) { Runtime.LoadAssembly(Assembly.GetExecutingAssembly()); } }
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); }
protected Microsoft.Scripting.Hosting.ScriptScope BuildPythonScope() { var engine = IronPython.Hosting.Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptScope scope = engine.CreateScope(); string wordpool_text = Resources.Load <TextAsset>("nopandas").text; var source = engine.CreateScriptSourceFromString(wordpool_text); source.Execute(scope); return(scope); }
/// <summary> /// Constructor. Creates a Python engine and a main scope where scripts can /// be executed. Also creates modules that can be added in the main scope. /// The standard output channel is changed in the constructor so that /// logging can be done to the provided console via the LogToConsole /// delegate. /// </summary> /// <param name="logToConsole"> /// Function used to log to console. Injected to ScriptEngine.\ /// </param> public ScriptEngine(LogToConsole logToConsole) { _logToConsole = logToConsole; _engine = Python.CreateEngine(); // Create the main scope _mainScope = _engine.CreateScope(); // This expression is used when initializing the scope. Changing the // standard output channel. Needs the function 'write' to be defined. string initExpression = @" import sys sys.stdout = standardOutput"; _mainScope.SetVariable("standardOutput", this); // Run initialization, also executes the main config file. ExecuteScript(initExpression); }
// 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); }
private static void InitPythonFunctions() { bool needToAddSearchPath = (engine == null); engine = engine ?? ScriptUtil.CreatePythonEngine(); if (needToAddSearchPath) { var scriptsFolderPath = BatchRvt.GetBatchRvtScriptsFolderPath(); ScriptUtil.AddSearchPaths(engine, new[] { scriptsFolderPath }); } pathUtilModuleScope = pathUtilModuleScope ?? IronPythonHosting.Python.ImportModule(engine, "path_util"); PYTHON_FUNCTION_ExpandedFullNetworkPath = PYTHON_FUNCTION_ExpandedFullNetworkPath ?? pathUtilModuleScope.GetVariable("ExpandedFullNetworkPath"); revitFileListModuleScope = revitFileListModuleScope ?? IronPythonHosting.Python.ImportModule(engine, "revit_file_list"); PYTHON_FUNCTION_RevitFileInfo = PYTHON_FUNCTION_RevitFileInfo ?? revitFileListModuleScope.GetVariable("RevitFileInfo"); revitFileVersionModuleScope = revitFileVersionModuleScope ?? IronPythonHosting.Python.ImportModule(engine, "revit_file_version"); PYTHON_FUNCTION_GetRevitVersionNumberTextFromRevitVersionText = PYTHON_FUNCTION_GetRevitVersionNumberTextFromRevitVersionText ?? revitFileVersionModuleScope.GetVariable("GetRevitVersionNumberTextFromRevitVersionText"); }
private void Application_Startup(object sender, StartupEventArgs e) { this.RootVisual = new MainPage(); var runtime = Silverlight.DynamicEngine.CreateRuntime(); _python = runtime.GetEngine("python"); _scope = _python.CreateScope(); _repl = Silverlight.Repl.Show(_python, _scope); _scope.SetVariable("app", this); try { test("Execute strings", "4", "2 + 2"); test("Import .NET namespace", "hi", @"import System System.String('hi')"); _python.Execute(@"import foo foo.test(app) foo.test_import(app)", _scope); } catch(Exception ex) { _repl.OutputBuffer.WriteLine("[FAIL]"); _repl.OutputBuffer.Write(_python.GetService<Hosting.ExceptionOperations>().FormatException(ex)); } }
/// <summary> /// Replaces existing one with the provided /// </summary> /// <param name="scope">New scope to replace the old one with</param> /// <returns>old scope for backup purposes</returns> public static Microsoft.Scripting.Hosting.ScriptScope PySwitchScope(ScriptScope scope) { Microsoft.Scripting.Hosting.ScriptScope old = ipy.EngineScope; ipy.EngineScope = scope; return(old); }
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); * } */ }
public IronPython.Runtime.List GenerateListsOptionalCategory(int numberOfLists, int lengthOfEachList, bool isCategoryPool, System.Random rng, bool isTwoParter, bool isEvenNumberSession, string participantCode) { //////////////////////Load the python wordpool code Microsoft.Scripting.Hosting.ScriptScope scope = BuildPythonScope(); //////////////////////Load the word pool IronPython.Runtime.List all_words; if (isCategoryPool) { all_words = ReadWordsFromPoolTxt("ram_categorized_en", isCategoryPool); } else { all_words = ReadWordsFromPoolTxt("ram_wordpool_en", isCategoryPool); } //////////////////////For two part experiments, reliably shuffle according to participant name and construct halves, then shuffle again /// Otherwise, just shuffle if (isTwoParter) { System.Random reliable_random = new System.Random(participantCode.GetHashCode()); if (!isCategoryPool) { all_words = Shuffled(reliable_random, all_words); } else { all_words = CategoryShuffle(reliable_random, all_words, 12); } if (isEvenNumberSession) { all_words = (IronPython.Runtime.List)all_words.__getslice__(0, all_words.Count / 2); } else { all_words = (IronPython.Runtime.List)all_words.__getslice__(all_words.Count / 2, all_words.Count); } } if (isCategoryPool) { all_words = CategoryShuffle(rng, all_words, lengthOfEachList); } else { all_words = Shuffled(rng, all_words); } ////////////////////////////////////////////Call list creation functions from python //////////////////////Concatenate into lists with numbers var assign_list_numbers_from_word_list = scope.GetVariable("assign_list_numbers_from_word_list"); var words_with_listnos = assign_list_numbers_from_word_list(all_words, numberOfLists); //////////////////////Build type lists and assign tpyes IronPython.Runtime.List stim_nostim_list = new IronPython.Runtime.List(); for (int i = 0; i < STIM_LIST_COUNT; i++) { stim_nostim_list.Add("STIM"); } for (int i = 0; i < NONSTIM_LIST_COUNT; i++) { stim_nostim_list.Add("NON-STIM"); } stim_nostim_list = Shuffled(rng, stim_nostim_list); var assign_list_types_from_type_list = scope.GetVariable("assign_list_types_from_type_list"); var words_with_types = assign_list_types_from_type_list(words_with_listnos, BASELINE_LIST_COUNT, stim_nostim_list, num_ps: PS_LIST_COUNT); //////////////////////Build stim channel lists and assign stim channels IronPython.Runtime.List stim_channels_list = new IronPython.Runtime.List(); for (int i = 0; i < A_STIM_COUNT; i++) { stim_channels_list.Add(new IronPython.Runtime.PythonTuple(new int[] { 0 })); } for (int i = 0; i < B_STIM_COUNT; i++) { stim_channels_list.Add(new IronPython.Runtime.PythonTuple(new int[] { 1 })); } for (int i = 0; i < AB_STIM_COUNT; i++) { stim_channels_list.Add(new IronPython.Runtime.PythonTuple(new int[] { 0, 1 })); } stim_channels_list = Shuffled(rng, stim_channels_list); var assign_multistim_from_stim_channels_list = scope.GetVariable("assign_multistim_from_stim_channels_list"); var words_with_stim_channels = assign_multistim_from_stim_channels_list(words_with_types, stim_channels_list); ////////////////////Build amplitude index list and assign amplitude indeces IronPython.Runtime.List amplitude_index_list = new IronPython.Runtime.List(); int lists_per_amplitude_index = 0; if (AMPLITUDE_COUNT != 0) { lists_per_amplitude_index = STIM_LIST_COUNT / AMPLITUDE_COUNT; } for (int amplitude_index = 0; amplitude_index < AMPLITUDE_COUNT; amplitude_index++) { for (int i = 0; i < lists_per_amplitude_index; i++) { amplitude_index_list.Add(amplitude_index); } } amplitude_index_list = Shuffled(rng, amplitude_index_list); var assign_amplitudes_from_amplitude_index_list = scope.GetVariable("assign_amplitudes_from_amplitude_index_list"); var words_with_amplitude_indices = assign_amplitudes_from_amplitude_index_list(words_with_stim_channels, amplitude_index_list); return(words_with_amplitude_indices); }
public void ClearScope() { EngineScope = Engine.CreateScope(); }
public PythonAutoComplete(Microsoft.Scripting.Hosting.ScriptEngine engine, Microsoft.Scripting.Hosting.ScriptScope scope) { this.engine = engine; this.scope = scope; this.excludeCallables = false; }
public void ClearScope() { EngineScope = Engine.CreateScope(); }