static public void Initialize() { var entryDirectory = Core.GetEntryDirectory() + "/"; CSharpCodeProvider = new CSharpCodeProvider(new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }); CompilerParameters = new CompilerParameters(); CompilerParameters.GenerateInMemory = true; CompilerParameters.GenerateExecutable = false; CompilerParameters.ReferencedAssemblies.Add("System.dll"); CompilerParameters.ReferencedAssemblies.Add("System.Drawing.dll"); CompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); if (System.IO.File.Exists(entryDirectory + "Effekseer.exe")) { CompilerParameters.ReferencedAssemblies.Add(entryDirectory + "Effekseer.exe"); } if (System.IO.File.Exists(entryDirectory + "EffekseerInterface.dll")) { CompilerParameters.ReferencedAssemblies.Add(entryDirectory + "EffekseerInterface.dll"); } CompilerParameters.ReferencedAssemblies.Add(entryDirectory + "EffekseerCore.dll"); PythonEngine = ph.Python.CreateEngine(); }
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"); } }
private void SetupStdlib(Microsoft.Scripting.Hosting.ScriptEngine engine) { // ask PyRevitLoader to add it's resource ZIP file that contains the IronPython // standard library to this engine var tempExec = new PyRevitLoader.ScriptExecutor(); tempExec.AddEmbeddedLib(engine); }
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); }
public static void AddSearchPaths(ScriptingHosting.ScriptEngine engine, IEnumerable <string> additionalSearchPaths) { var searchPaths = engine.GetSearchPaths(); foreach (var path in additionalSearchPaths) { searchPaths.Add(path); } engine.SetSearchPaths(searchPaths); }
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); }
public PythonEngine( IReportServerReader reportServerReader, IReportServerWriter reportServerWriter, IReportServerRepository reportServerRepository, IFileSystem fileSystem, ILogger logger, ILogger scriptLogger) { if (reportServerReader == null) { throw new ArgumentNullException("reportServerReader"); } if (reportServerWriter == null) { throw new ArgumentNullException("reportServerWriter"); } if (reportServerRepository == null) { throw new ArgumentNullException("reportServerRepository"); } if (fileSystem == null) { throw new ArgumentNullException("fileSystem"); } if (logger == null) { throw new ArgumentNullException("logger"); } if (scriptLogger == null) { throw new ArgumentNullException("scriptLogger"); } this.mReportServerReader = reportServerReader; this.mReportServerWriter = reportServerWriter; this.mReportServerRepository = reportServerRepository; this.mFileSystem = fileSystem; this.mLogger = logger; this.mScriptLogger = scriptLogger; this.mAppDomain = AppDomain.CreateDomain("sandbox"); this.mScriptEngine = Python.CreateEngine(); this.mScriptEngine.Runtime.ImportModule("clr"); this.mEnginePath = Environment.CurrentDirectory; }
static public void Dispose() { if (CSharpCodeProvider != null) { CSharpCodeProvider.Dispose(); CSharpCodeProvider = null; } if (PythonEngine != null) { PythonEngine.Runtime.Shutdown(); PythonEngine = null; } }
public void SetUp() { var configFile = Path.GetFullPath(Uri.UnescapeDataString(new Uri(typeof(TestFixtureBase).Assembly.CodeBase).AbsolutePath)) + ".config"; Runtime = new ScriptRuntime(ScriptRuntimeSetup.ReadConfiguration(configFile)); _output = new MemoryStream(); _errorOutput = new MemoryStream(); Runtime.IO.SetOutput(_output, Encoding.ASCII); Runtime.IO.SetErrorOutput(_errorOutput, Encoding.ASCII); Engine = Runtime.GetEngine("ht"); LanguageContext = HostingHelpers.GetLanguageContext(Engine) as HappyLanguageContext; GlobalScope = Engine.CreateScope(); Assert.IsNotNull(GlobalScope); }
/// <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); }
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"); }
// 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 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)); } }
public static ScriptingHosting.ScriptScope CreateMainModule(ScriptingHosting.ScriptEngine engine) { var mainModuleScope = IronPythonHosting.Python.CreateModule(engine, "__main__"); return(mainModuleScope); }
public static void AddBuiltinVariables(ScriptingHosting.ScriptEngine engine, IEnumerable <KeyValuePair <string, object> > variables) { AddVariables(IronPythonHosting.Python.GetBuiltinModule(engine), variables); return; }
static IronRubyScript() { runtime = IronRuby.Ruby.CreateRuntime(); _rubyEngine = runtime.GetEngine("Ruby"); _scope = _rubyEngine.CreateScope(); }
static void Main() { var bx = new float[12]; var ax = new float[12]; LiquidDSPClass.liquid_iirdes(LiquidDSPClass.liquid_iirdes_filtertype.LIQUID_IIRDES_ELLIP, LiquidDSPClass.liquid_iirdes_bandtype.LIQUID_IIRDES_HIGHPASS, LiquidDSPClass.liquid_iirdes_format.LIQUID_IIRDES_SOS, 8, (float)(50.0 / 50000), 0.25f, 0.1f, 60f, bx, ax); var filepath = Path.GetFullPath(@"C:\Users\u12o24\Documents\Concerto_NVH"); var rawdata = new double[500001]; var sos1 = new double[24]; var zi_tmp = new double[8]; using (var br = new BinaryReader(new FileStream(Path.Combine(filepath, "rawdata.bin"), FileMode.Open))) { for (int ii = 0; ii < rawdata.Length; ii++) { rawdata[ii] = br.ReadDouble(); } }; /*using (var br = new BinaryReader(new FileStream(Path.Combine(filepath, "sos1.bin"), FileMode.Open))) * { * for (int ii = 0; ii < sos1.Length; ii++) sos1[ii] = br.ReadDouble(); * }; * using (var br = new BinaryReader(new FileStream(Path.Combine(filepath, "zi.bin"), FileMode.Open))) * { * for (int ii = 0; ii < zi_tmp.Length; ii++) zi_tmp[ii] = br.ReadDouble(); * };*/ using (var br = new BinaryReader(new FileStream(Path.Combine(filepath, "ziliquid.bin"), FileMode.Open))) { for (int ii = 0; ii < zi_tmp.Length; ii++) { zi_tmp[ii] = br.ReadDouble(); } }; using (var bw = new BinaryWriter(new FileStream(Path.Combine(filepath, "Liquid.bin"), FileMode.Create))) { for (int ii = 0; ii < bx.Length; ii++) { bw.Write(bx[ii]); } for (int ii = 0; ii < ax.Length; ii++) { bw.Write(ax[ii]); } }; int L = 4; var b = new double[L][]; var a = new double[L][]; var zi = new double[L][]; for (int ii = 0; ii < L; ii++) { b[ii] = new double[3]; a[ii] = new double[3]; zi[ii] = new double[2]; for (int jj = 0; jj < 3; jj++) { //b[ii][jj] = sos1[jj * L + ii]; //a[ii][jj] = sos1[jj * L + L * 3 + ii]; b[ii][jj] = bx[ii * 3 + jj]; a[ii][jj] = ax[ii * 3 + jj]; if (jj < 2) { zi[ii][jj] = zi_tmp[ii * 2 + jj]; } } } var filtered = rawdata; for (int ii = 0; ii < L; ii++) { filtered = LiquidDSPClass.FiltFilt(filtered, b[ii], a[ii], zi[ii]); } using (var bw = new BinaryWriter(new FileStream(Path.Combine(filepath, "filtered_liquid.bin"), FileMode.Create))) { for (int ii = 0; ii < filtered.Length; ii++) { bw.Write(filtered[ii]); } }; string test1 = "C:\\Programs\\pd"; Console.WriteLine(test1.Replace('\\', '/')); Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine(); // Print the default search paths System.Console.Out.WriteLine("Search paths:"); ICollection <string> searchPaths = pythonEngine.GetSearchPaths(); foreach (string path in searchPaths) { System.Console.Out.WriteLine(path); } System.Console.Out.WriteLine(); var doublearray = new double[3] { 3.5, 2.2, 0.7 }; // Now modify the search paths to include the directory from // which we execute the script searchPaths.Add("..\\.."); pythonEngine.SetSearchPaths(searchPaths); var scope = pythonEngine.CreateScope(); scope.SetVariable("externalString", "how do you do?"); scope.SetVariable("doublearray", doublearray); Microsoft.Scripting.Hosting.ScriptSource pythonScript = //pythonEngine.CreateScriptSourceFromString("print 'Hello World!'"); pythonEngine.CreateScriptSourceFromFile("..\\..\\HelloWorld.py"); pythonScript.Execute(scope); Console.WriteLine(scope.GetVariable("helloWorldString")); var arrayfrompython = (double[])scope.GetVariable("doublearray"); Console.WriteLine(arrayfrompython[2]); Console.Read(); //Console.WriteLine() /*var x = new double[10] { 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 }; * var y = new double[10] { 5000, 6000, 4000, 3500, 3000, 2500, 1500, 1700, 1000, 500 }; * * var test = Concerto.ProcessLQ_mono(new XY_Data { xdata = x, ydata = y });*/ /*var arr1 = new int[3] { 7, 4, 3 }; * var arr2 = new int[3] { 1, 2, 3 }; * Array.Sort(arr1, arr2);*/ //var test1 = GeneralMath.Nextpow2(50000 / 1); //var outstr = ""; //NVHFunctions.F_octave f0 = Concerto.CalcCornerFreqs(6, 65536, 2*65536); //for (int ii = 0; ii < f0.f0.Length; ii++) if (f0.f0[ii] <= 20000 && f0.f0[ii] >= 20) outstr += Math.Round(f0.f0[ii], 1).ToString(CultureInfo.InvariantCulture) + ", "; //Console.WriteLine(outstr); string filename = "C:\\Users\\u12o24\\Documents\\nvhdebugdata.xls"; NVHPackage obj; using (var filestream = new FileStream(filename, FileMode.Open)) { using (var xmlreader = XmlReader.Create(filestream)) { XmlSerializer serializer = new XmlSerializer(typeof(NVHPackage)); obj = (NVHPackage)serializer.Deserialize(xmlreader); xmlreader.Close(); filestream.Close(); } } //obj.Paramset.Delta_t = 0.1; //obj.Paramset.Delta_f = 4; //var test = CalcAPSData(obj.Rawdata.ToArray(), obj.Enginespeed, obj.X0, new CATimeStamps(), obj.Paramset); //obj.Paramset.Delta_t = 1; //var test = CalcOrderSpectra(obj.Rawdata.ToArray(), new XY_Data(), obj.Enginespeed, obj.X0, new CATimeStamps(), obj.Paramset); //var test = GetXAxis((int)obj.Rawdata[0], new XY_Data(), obj.X0, new CATimeStamps(), obj.Paramset); //var test = CalcOverallLevel(obj.Rawdata.ToArray(), new XY_Data(), obj.X0, new CATimeStamps(), obj.Paramset); //Console.WriteLine(test.dimensions[0]); //Console.WriteLine(test.dimensions[1]); /* * var x = new double[11]; * var y = new double[11]; * for (int ii = 0; ii < x.Length; ii++) * { * x[ii] = ii; * y[ii] = Math.Sin(ii); * Console.WriteLine("x: " + x[ii] + "\t y: " + y[ii]); * } * var xq = new double[49]; * for (int ii = 0; ii < xq.Length; ii++) xq[ii] = 0.25 * ii; * var yq = GeneralMath.Interp1_linear(x, y, xq, true); * for (int ii = 0; ii < yq.Length; ii++) Console.WriteLine("xq: " + xq[ii] + "\t yq:" + yq[ii]); * * var aps = new NVHLibrary.APS(); * var bplevel = new NVHLibrary.BandPassLevel(); */ /*double[] test = new double[5] { 4, 5, 11, 3, -2 }; * var result = NVHFunctions.GeneralMath.Cumsum(test); * for (int ii = 0; ii < result.Length; ii++) Console.WriteLine(result[ii]);*/ Console.ReadKey(); }
public PythonAutoComplete(Microsoft.Scripting.Hosting.ScriptEngine engine, Microsoft.Scripting.Hosting.ScriptScope scope) { this.engine = engine; this.scope = scope; this.excludeCallables = false; }
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 PythonInterop() { _engine = Python.CreateEngine(); _scope = _engine.CreateScope(); }
// Start is called before the first frame update void Start() { engine = UnityPython.CreateEngine(); }
internal ScriptScope(ScriptEngine engine, Scope scope) { Assert.NotNull(engine, scope); _scope = scope; _engine = engine; }