/// <summary> /// 用户自定义Python脚本 /// </summary> /// <param name="source"></param> /// <returns></returns> public static string RepairFun_PythonScript(string handler, string source) { if (source == "") { return(""); } Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString( $"import textRepairPlugins.{handler} as customHandler\n" + "ResultStr = customHandler.process(SourceStr)\n" ); Microsoft.Scripting.Hosting.ScriptScope scope = pythonEngine.CreateScope(); scope.SetVariable("SourceStr", source); try { pythonScript.Execute(scope); } catch (Exception e) { return(e.Message); } return((string)scope.GetVariable("ResultStr")); }
public ImgInterpreter() { path = ""; script = "scripts\\_default.py"; py = Python.CreateEngine(); // allows to run ironpython programs s = py.CreateScope(); // you need this to get the variables }
private void Start() { engine = Python.CreateEngine(); engine.Runtime.LoadAssembly(typeof(GameObject).Assembly); engine.Runtime.LoadAssembly(typeof(Image).Assembly); //engine.ImportModule(""); scope = engine.CreateScope(); scope.SetVariable("pyConsole", pyConsole); engine.Execute(pythonScript, scope); //var scope = engine.ExecuteFile(path); int counter = scope.GetVariable <int>("counter"); Debug.Log(counter); float timeBackup = scope.GetVariable <float>("timeBackup"); Debug.Log(timeBackup); Debug.LogError("Error test"); Debug.LogWarning("warning\nTest"); //TestInstance(); //TestInstance(); //GameObject.Find("Player").transform.GetChild(0).GetComponent("MeshRenderer").sharedMaterial.color = Color.black; //GameObject.Find("Player").transform.localRotation = Quaternion.Euler(0, 0, 90); //Camera.main.transform.position = new Vector3(2,2,-5); //string variables = string.Join(",", scope.GetVariableNames().ToArray()); //Debug.Log("variables: " + variables); }
public static void WriteInt32(BinaryWriter binw, Microsoft.Scripting.Hosting.ScriptScope s, string pyVar, int value) { if (s.ContainsVariable(pyVar + "_OFFSET")) { binw.BaseStream.Seek(s.GetVariable(pyVar + "_OFFSET"), SeekOrigin.Begin); } if (s.ContainsVariable(pyVar + "_TYPE")) { string type = s.GetVariable(pyVar + "_TYPE"); switch (type) { case "TRAILED_STRING": char trail = char.Parse(s.GetVariable(pyVar + "_TRAIL")); char[] value2 = value.ToString().ToCharArray(); binw.Write(value2); binw.Write(trail); break; case "INT16": binw.Write((Int16)value); break; default: binw.Write(value); break; } } else { binw.Write(value); } }
static void Main(string[] args) { Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString( "helloWorldString = 'Hello World!'\n" + "print helloWorldString\n" + "print externalString" ); Microsoft.Scripting.Hosting.ScriptScope scope = pythonEngine.CreateScope(); scope.SetVariable("externalString", "How do you do?"); pythonScript.Execute(scope); System.Console.Out.WriteLine(); System.Console.Out.WriteLine("List of variables in the scope:"); foreach (string name in scope.GetVariableNames()) { System.Console.Out.Write(name + " "); } System.Console.Out.WriteLine(); System.Console.Out.WriteLine(); System.Console.Out.WriteLine("Variable values:"); System.Console.Out.WriteLine("helloWorldString: " + scope.GetVariable("helloWorldString")); System.Console.Out.WriteLine("externalString: " + scope.GetVariable("externalString")); }
//interface //constructor public Console(IConsoleTarget target) { if (target == null) { throw new ArgumentException("target cannot be null"); } title = target.ConsoleTitle; this.target = target; var targetScope = target.GetScope(); var locals = new IronPython.Runtime.PythonDictionary(); foreach (var name in targetScope.GetVariableNames()) { locals[name] = targetScope.GetVariable(name); } scope = Py.CreateScope(); scope.SetVariable("_locals", locals); var ops = scope.Engine.Operations; string init_script = System.IO.File.ReadAllText(Util.ResourcePath("PythonScripts/initialize_new_console.py")); Py.Engine.Execute(init_script, scope); python_output_buffer = scope.GetVariable <IronPython.Modules.PythonIOModule.StringIO>("output_buffer"); python_compile_command = scope.GetVariable <IronPython.Runtime.PythonFunction>("compile_command"); python_console_run_code = scope.GetVariable <IronPython.Runtime.PythonFunction>("console_run_code"); output = new LineBuffer(new string[] { ">>> " }); input = new LineBuffer(new string[] { "" }); editor = new StringBuilder(500); multilineEditor = new StringBuilder(500); _currentInputIndex = 0; _editorCursor = 0; }
public Script() { engine = Python.CreateEngine(); scope = engine.CreateScope(); scope.SetVariable("cs", MainV2.cs); scope.SetVariable("Script", this); Console.WriteLine(DateTime.Now.Millisecond); engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope); Console.WriteLine(DateTime.Now.Millisecond); engine.CreateScriptSourceFromString("print cs.roll").Execute(scope); Console.WriteLine(DateTime.Now.Millisecond); object thisBoxed = MainV2.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 Script(bool redirectOutput = false) { Dictionary <string, object> options = new Dictionary <string, object>(); options["Debug"] = true; if (engine != null) { engine.Runtime.Shutdown(); } engine = Python.CreateEngine(options); scope = engine.CreateScope(); var all = System.Reflection.Assembly.GetExecutingAssembly(); engine.Runtime.LoadAssembly(all); 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); 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 Script(bool redirectOutput = false) { 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"); engine.SetSearchPaths(paths); scope = engine.CreateScope(); var all = System.Reflection.Assembly.GetExecutingAssembly(); engine.Runtime.LoadAssembly(all); 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); 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); } */ }
private void callPythonCode() { var options = new Dictionary <string, object>(); options["Frames"] = true; options["FullFrames"] = true; //create ironpython engine and scope Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine(options); Microsoft.Scripting.Hosting.ScriptScope scope = py.CreateScope(); //add python folder to pythonpath string pythonCodePath = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/"; string pyGDPPath = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/pyGDP-master/"; string OWSPath = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/owslib/"; string owslibPath = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/OWS/OWSLib-0.8.6/owslib/"; string libPath = Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/Lib/"; ICollection <string> paths = py.GetSearchPaths(); paths.Add(pythonCodePath); paths.Add(pyGDPPath); paths.Add(OWSPath); paths.Add(owslibPath); paths.Add(libPath); py.SetSearchPaths(paths); //store variables in scope scope.SetVariable("futOne", futOne); scope.SetVariable("futTwo", futTwo); scope.SetVariable("futThree", futThree); scope.SetVariable("futFour", futFour); scope.SetVariable("futFive", futFive); scope.SetVariable("futSix", futSix); scope.SetVariable("histOne", histOne); scope.SetVariable("histTwo", histTwo); scope.SetVariable("filePath", filePath); //run code py.ExecuteFile(Application.StartupPath + "/Plugins/ClimateAnalysis/IronPython/module1.py", scope); string outputPathF2 = scope.GetVariable("outputPathF2").ToString(); string outputPathH1 = scope.GetVariable("outputPathH1").ToString(); //retrieve climate data filePath = filePath.Remove(filePath.Length - 9); string urlF2 = "http://cida.usgs.gov:80/gdp/process/RetrieveResultServlet?id=" + outputPathF2; WebClient webClient = new WebClient(); webClient.DownloadFile(urlF2, @filePath + "FutureClimateData.csv"); string urlH1 = "http://cida.usgs.gov:80/gdp/process/RetrieveResultServlet?id=" + outputPathH1; WebClient webClient2 = new WebClient(); webClient2.DownloadFile(urlH1, @filePath + "HistoricalClimateData.csv"); return; }
private void Start() { engine = Python.CreateEngine(); engine.Runtime.LoadAssembly(typeof(GameObject).Assembly); scope = engine.CreateScope(); scope.SetVariable("pyConsole", pyConsole); scope.SetVariable("unityEvents", unityMethodsEvents); engine.Execute(pythonScript, scope); }
static void Main(string[] args) { Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptScope s = py.CreateScope(); py.Execute( @"import numpy as np incomes = np.random.normal(27000, 15000, 10000) x = np.mean(incomes)" , s); }
public Script(bool redirectOutput = false) { 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(@"C:\Program Files (x86)\IronPython 2.7\Lib"); //Allows for additional libraries from IronPython. Requires download from https://ironpython.codeplex.com/releases/view/90087 engine.SetSearchPaths(paths); scope = engine.CreateScope(); var all = System.Reflection.Assembly.GetExecutingAssembly(); engine.Runtime.LoadAssembly(all); scope.SetVariable("MAV", MainV2.comPort); scope.SetVariable("cs", MainV2.comPort.MAV.cs); scope.SetVariable("Script", this); scope.SetVariable("mavutil", this); //engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope); //Unneeded testing //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 override void Execute(string src, Uri uri, HttpListenerContext p, WebConfig wc, StreamWriter sw) { Microsoft.Scripting.Hosting.ScriptEngine py = IronRuby.Ruby.CreateEngine(); Microsoft.Scripting.Hosting.ScriptScope s = py.CreateScope(); var sapi = new StandardScriptApi(uri, p, sw); foreach (var item in sapi.Variables) { s.SetVariable(item.Key, item.Value); } py.Execute(src, s); }
static IPyInterface() { //Create the python execution engine engine = IronPython.Hosting.Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptScope scriptScope = engine.CreateScope(); //Link to the scripts that create the Beach_Interface object string strInitialize = "import Interface"; string strGet_interface = "Interface.Interface"; //Return the Beach_Interface object engine.Execute(strInitialize, scriptScope); ipyInterface = engine.Execute(strGet_interface, scriptScope); }
static void Main(string[] args) { Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptScope s = py.CreateScope(); // add paths to where your libs are installed var libs = new[] { @"c:\path\to\lib1", @"c:\path\to\lib2" }; py.SetSearchPaths(libs); py.Execute( @"import numpy as np incomes = np.random.normal(27000, 15000, 10000) x = np.mean(incomes)" , s); }
private static void AddScopeMethods(IResources resources, Microsoft.Scripting.Hosting.ScriptScope scope) { Action <string> log = (logText) => resources.Logger.LogInformation($"[Python] - {logText}"); Func <string, int> sql = (sqlText) => resources.DbTransaction.Connection.Execute(sqlText, transaction: resources.DbTransaction, commandTimeout: resources.Context.MaximumTimeout); Action commit = () => resources.DbTransaction.Commit(); Action rollback = () => resources.DbTransaction.Rollback(); Func <string, IEnumerable <IronPython.Runtime.PythonDictionary> > query = (sqlText) => resources.DbTransaction.Connection.Query( sqlText, transaction: resources.DbTransaction, commandTimeout: resources.Context.MaximumTimeout ).ToList().Select(row => (row as IDictionary <string, object>).ToPythonDictionary()).ToList(); scope.SetVariable("log", log); scope.SetVariable("sql", sql); scope.SetVariable("commit", commit); scope.SetVariable("rollback", rollback); scope.SetVariable("query", query); }
public override void Initialize() { Func <TreeNode <string>, JObject> nodeToJObject = (node) => { JObject obj = new JObject(); TreeNode <string> .TreeNodeToJson(node, obj); return(obj); }; _scriptEngine = Python.CreateEngine(); _scope = _scriptEngine.CreateScope(); // Execute main script { string entryFile = Data.GetValue("entry"); var src = _scriptEngine.CreateScriptSourceFromFile(entryFile); Logger.Info("Main script({0}) loading...", Path.GetFileName(entryFile)); src.Execute(_scope); // Setting global variables SetVariable("ScriptName", Name); // globalObjects의 이름 SetVariable("RoseApi", _scriptApi); // ScriptAPI instance SetVariable("ServerConfig", nodeToJObject(Starter.Config)); // Config 전체 SetVariable("ScriptConfig", nodeToJObject(Data)); // globalObjects에 정의된 data 항목 // Predefined function FnRoseEntry = GetVariable("roseEntry"); FnBeforeRequestHandling = GetVariable("beforeRequestHandling"); // Request 핸들러 FnBeforeResponseHandling = GetVariable("beforeResponseHandling"); // Response 핸들러 // Call entry function if (FnRoseEntry != null) { FnRoseEntry(); } } }
public Script() { Dictionary <string, object> options = new Dictionary <string, object>(); options["Debug"] = true; if (engine != null) { engine.Runtime.Shutdown(); } engine = Python.CreateEngine(options); scope = engine.CreateScope(); var all = System.Reflection.Assembly.GetExecutingAssembly(); engine.Runtime.LoadAssembly(all); scope.SetVariable("MAV", MainV2.comPort); scope.SetVariable("cs", MainV2.comPort.MAV.cs); scope.SetVariable("Script", this); scope.SetVariable("mavutil", this); engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope); engine.CreateScriptSourceFromString("print cs.roll").Execute(scope); 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 static ModuleContext GetModuleContext(this ScriptScope scriptScope) { var scope = (Microsoft.Scripting.Runtime.Scope) typeof(ScriptScope).InvokeMember("_scope", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, scriptScope, null); DefaultContext.DefaultPythonContext.EnsureScopeExtension(scope); var ext = scope.GetExtension(DefaultContext.DefaultPythonContext.ContextId); if (ext == null) { return(null); } Type PythonScopeExtension = typeof(PythonContext).Assembly.GetType("IronPython.Runtime.PythonScopeExtension"); ModuleContext mod = (ModuleContext)PythonScopeExtension.GetProperty("ModuleContext").GetValue(ext, null); return(mod); }
/// <summary> /// Imports the chosen image /// </summary> /// <param name="imgpath">path to image</param> /// <param name="scriptpath">script path</param> /// <returns></returns> public Bitmap Load(string imgpath, string scriptpath) { py = Python.CreateEngine(); s = py.CreateScope(); path = imgpath; img = new Bitmap(4, 4); script = scriptpath; if (scriptpath.Length > 100) { py.Execute(script, s); } else { py.ExecuteFile(script, s); } LoadImg(); return(img); }
public void runScript() { String path = @"c:\pythonSpeedTest.py"; var source = System.IO.File.ReadAllText(path); Microsoft.Scripting.Hosting.ScriptEngine py = Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptScope scope = py.CreateScope(); var paths = py.GetSearchPaths(); paths.Add(@"c:\Program Files (x86)\IronPython 2.7\Lib"); py.SetSearchPaths(paths); try { py.Execute(source); }catch (Exception ex) { Console.WriteLine("Error occured in python script\n" + ex); Console.ReadKey(); return; } }
public bool IronPython(Parameter parameter) { Microsoft.Scripting.Hosting.ScriptEngine engine = global::IronPython.Hosting.Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptScope scope = engine.CreateScope(); scope.SetVariable("n", parameter.Numbers); List <int> results = new List <int>(parameter.Numbers.Length); foreach (int number in parameter.Numbers) { int result = engine.Execute <int>(parameter.Statements[number], scope); results.Add(result); } return(Assert(results, parameter.Sum)); }
public Script() { Dictionary<string, object> options = new Dictionary<string, object>(); options["Debug"] = true; if (engine != null) engine.Runtime.Shutdown(); engine = Python.CreateEngine(options); scope = engine.CreateScope(); var all = System.Reflection.Assembly.GetExecutingAssembly(); engine.Runtime.LoadAssembly(all); scope.SetVariable("MAV", MainV2.comPort); scope.SetVariable("cs", MainV2.comPort.MAV.cs); scope.SetVariable("Script", this); scope.SetVariable("mavutil", this); engine.CreateScriptSourceFromString("print 'hello world from python'").Execute(scope); engine.CreateScriptSourceFromString("print cs.roll").Execute(scope); 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); } }
static void Main(string[] args) { Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine(); ICollection <string> searchPaths = pythonEngine.GetSearchPaths(); searchPaths.Add("..\\.."); pythonEngine.SetSearchPaths(searchPaths); Microsoft.Scripting.Hosting.ScriptScope scope = IronPython.Hosting.Python.ImportModule(pythonEngine, "HelloWorldModule"); dynamic printHelloWorldFunction = scope.GetVariable("PrintHelloWorld"); printHelloWorldFunction(); dynamic printMessageFunction = scope.GetVariable("PrintMessage"); printMessageFunction("Goodbye!"); dynamic addFunction = scope.GetVariable("Add"); System.Console.Out.WriteLine("The sum of 1 and 2 is " + addFunction(1, 2)); }
public static int ReadInt32(BinaryReader binr, Microsoft.Scripting.Hosting.ScriptScope s, string pyVar) { int rVar = 0; bool skip = false; FileStream fs = (FileStream)binr.BaseStream; string script = Path.GetExtension(fs.Name).Remove(0, 1).ToUpper(); if (script == pyVar.Split('_')[0]) { skip = true; } if (s.ContainsVariable(pyVar + "_OFFSET")) { binr.BaseStream.Seek(s.GetVariable(pyVar + "_OFFSET"), SeekOrigin.Begin); } if (!skip && s.ContainsVariable(pyVar)) { rVar = s.GetVariable(pyVar); } else { if (s.ContainsVariable(pyVar + "_TYPE")) { string type = s.GetVariable(pyVar + "_TYPE"); switch (type) { case "TRAILED_STRING": char trail = char.Parse(s.GetVariable(pyVar + "_TRAIL")); string value = ""; char add = ' '; while (true) { add = binr.ReadChar(); if (add != trail) { value += add; } else { if (!skip) { rVar = int.Parse(value); } break; } } break; case "INT16": rVar = binr.ReadInt16(); break; case "BYTE": rVar = binr.ReadByte(); break; default: rVar = 0; break; } } else { rVar = binr.ReadInt32(); } } if (skip) { return(0); } return(rVar); }
// private readonly Scope _scope; // public VBScriptDlrScope(Scope scope) public VBScriptDlrScope(Microsoft.Scripting.Hosting.ScriptScope scope) { _scope = scope; }
private void InitializeIronPython() { pyEngine = IronPython.Hosting.Python.CreateEngine(); pyScope = pyEngine.CreateScope(); pyScope.SetVariable("qst", QST); }
private void InitPythonPlugin(Package p, ref Microsoft.Scripting.Hosting.ScriptEngine engine, ref Microsoft.Scripting.Hosting.ScriptScope scope) { if (System.IO.File.Exists(p.Path + "\\__init__.py")) { engine.ExecuteFile(p.Path + "\\__init__.py", scope); } else { throw new InvalidOperationException("Unable to find file __init__.py"); } }
/// <summary> /// Export image to chosen format /// </summary> /// <param name="path">output path</param> /// <param name="scriptpath">script path</param> public void ExportImg(string path, string scriptpath) { py = Python.CreateEngine(); s = py.CreateScope(); //py.ExecuteFile(scriptpath, s); if (scriptpath.Length > 100) { py.Execute(scriptpath, s); } else { py.ExecuteFile(scriptpath, s); } BinaryWriter binr; fs = new FileStream(path, FileMode.Create); binr = new BinaryWriter(fs); pixelFormat = s.GetVariable("IMG_PIXEL_FORMAT"); pixelFormat = pixelFormat.ToUpper(); if (pixelFormat.Length < 4 && BPP == 32) { pixelFormat += "A"; } int w1 = 0; List <string> order = s.GetVariable("WRITE_ORDER"); for (int i = 0; i < order.Count; i++) { switch (order[i]) { case "FILE_MAGIC": List <Byte> magic2 = s.GetVariable("FILE_MAGIC"); for (int j = 0; j < magic2.Count; j++) { binr.Write(magic2[j]); } break; case "FILE_SIZE": /*if (img.Width % 2 > 0) * w1 = 1; * binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin); * binr.Write(0x36 + ((img.Width + w1) * img.Height * bpp / 8));*/ break; case "IMG_PIXELS_LEN": if (img.Width % 2 > 0) { w1 = 1; } binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin); binr.Write((img.Width + w1) * img.Height * BPP / 8); break; /*case "FILE_HEADER_SIZE": * binr.Seek(s.GetVariable("FILE_HEADER_SIZE_OFFSET"), SeekOrigin.Begin); * binr.Write(s.GetVariable("FILE_HEADER_SIZE")); * break;*/ case "IMG_WIDTH": //binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin); //binr.Write(img.Width); VarWriter.WriteInt32(binr, s, order[i], img.Width); break; case "IMG_HEIGHT": //binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin); //binr.Write(img.Height); VarWriter.WriteInt32(binr, s, order[i], img.Height); break; case "IMG_BPP": binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin); binr.Write(BPP); break; case "IMG_PIXELS": if (s.ContainsVariable("IMG_PIXELS_OFFSET")) { binr.Seek(s.GetVariable("IMG_PIXELS_OFFSET"), SeekOrigin.Begin); } //int red = 0, green = 0, blue = 0; w1 = 0; if (s.ContainsVariable("IMG_UNEVEN_PADDING")) { if (s.GetVariable("IMG_UNEVEN_PADDING")) { if (img.Width % 2 > 0) { w1 = 1; } } } if (s.ContainsVariable("IMG_UPSIDE_DOWN")) { if (s.GetVariable("IMG_UPSIDE_DOWN")) { img = Operations.FlipVertical(img); } } List <byte> rgb = new List <byte>(); if (s.ContainsVariable("IMG_PIXELS_HANDLER")) { if (s.GetVariable("IMG_PIXELS_HANDLER")) { for (int j = 0; j < img.Height; j++) { for (int q = 0; q < img.Width + w1; q++) { if (q < img.Width) { for (int c = 0; c < pixelFormat.Length; c++) { if (pixelFormat[c] == 'B') { rgb.Add(img.GetPixel(q, j).B); } if (pixelFormat[c] == 'G') { rgb.Add(img.GetPixel(q, j).G); } if (pixelFormat[c] == 'R') { rgb.Add(img.GetPixel(q, j).R); } if (pixelFormat[c] == 'A') { rgb.Add(img.GetPixel(q, j).A); } } } } } var SavePixels = s.GetVariable("SavePixels"); IList <object> rgbp = new List <object>(); for (int z = 0; z < rgb.Count; z++) { rgbp.Add(rgb[z]); } List <byte> rgbl = SavePixels(rgbp, img.Width, img.Height, BPP); if (rgbl.Count < img.Width * img.Height) { binr.Write(rgb.ToArray()); } else { binr.Write(rgbl.ToArray()); } } } else { for (int j = 0; j < img.Height; j++) { for (int q = 0; q < img.Width + w1; q++) { if (q < img.Width) { for (int c = 0; c < pixelFormat.Length; c++) { if (pixelFormat[c] == 'B') { binr.Write(img.GetPixel(q, j).B); } if (pixelFormat[c] == 'G') { binr.Write(img.GetPixel(q, j).G); } if (pixelFormat[c] == 'R') { binr.Write(img.GetPixel(q, j).R); } if (pixelFormat[c] == 'A') { binr.Write(img.GetPixel(q, j).A); } } } else { for (int c = 0; c < pixelFormat.Length; c++) { binr.Write((byte)0); } } } } } if (s.ContainsVariable("IMG_UPSIDE_DOWN")) { if (s.GetVariable("IMG_UPSIDE_DOWN")) { img = Operations.FlipVertical(img); } } break; default: //binr.Seek(s.GetVariable(order[i] + "_OFFSET"), SeekOrigin.Begin); //binr.Write(s.GetVariable(order[i])); VarWriter.WriteScriptVar(binr, s, order[i]); break; } } if (order.Contains("FILE_SIZE")) { int size = (int)binr.BaseStream.Position; binr.Seek(s.GetVariable("FILE_SIZE_OFFSET"), SeekOrigin.Begin); binr.Write(size); } binr.Close(); fs.Close(); }
public PythonScriptEngine() { engine = Python.CreateEngine(); scope = engine.CreateScope(); }
public void ClearScope() { _scope = _engine.CreateScope(); Init(); EchoLine("Scope cleared."); }
/// <summary> /// Clears the variables of the scope of the script. /// </summary> public override void ClearScopeVariables() { this.Scope = this.Engine.CreateScope(); this.Scope.SetVariable(Command, this.ScriptingProxy); this.UpdateScopeVariables(); }
private void MainForm_Load(object sender, EventArgs e) { textBox.Highlighter = Highlighters.Ruby; textBox.Images = templateBMPs; engine = IronRuby.Ruby.CreateEngine(); ui = new UI(this); scope = engine.CreateScope(); scope.SetVariable("ui", ui); // Ctrl + R で今表示されているスクリプトを実行 // Ctrl + Esc で実行終了 // Ctrl + RPrintScreen でスクリーンショットを撮る AddHotKeyAction(MOD_WIN, Keys.S, "スローモーションで実行", () => { ui.slowPlayFlag = true; Run(textBox.Text); }); AddHotKeyAction(MOD_WIN, Keys.Q, "実行停止", () => 停止SToolStripMenuItem_Click(null, null)); AddHotKeyAction(MOD_CONTROL, Keys.PrintScreen, "スクリーンショットを撮る", () => new BlackForm().takeScreenshot(this)); LoadConfigData(); }