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); } */ }
/// <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")); }
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")); }
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 void runScript(string script) { try { engine.CreateScriptSourceFromString(script).Execute(scope); } catch (Exception e) { System.Windows.Forms.MessageBox.Show("Error running script " + e.Message); } }
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 void runScript(string script) { try { Console.WriteLine("Run Script " + scope); engine.CreateScriptSourceFromString(script).Execute(scope); Console.WriteLine("Run Script Done"); } catch (Exception e) { CustomMessageBox.Show("Error running script " + e.Message); } }
private static PyAst.PythonAst ParsePythonSource(Microsoft.Scripting.Hosting.ScriptEngine engine, string code) { var src = engine.CreateScriptSourceFromString(code); var sourceUnit = Microsoft.Scripting.Hosting.Providers.HostingHelpers.GetSourceUnit(src); var langContext = Microsoft.Scripting.Hosting.Providers.HostingHelpers.GetLanguageContext(engine); var compilerCtxt = new Microsoft.Scripting.Runtime.CompilerContext( sourceUnit, langContext.GetCompilerOptions(), Microsoft.Scripting.ErrorSink.Default); var parser = IronPython.Compiler.Parser.CreateParser( compilerCtxt, (IronPython.PythonOptions)langContext.Options ); return(parser.ParseFile(false)); }
private GameObject CreateObject(string expression, float x, float y) { expression = "from MarioBros import *\r\nfrom Microsoft.Xna.Framework import *\r\n" + expression; var source = scriptEngine.CreateScriptSourceFromString(expression); var scope = scriptEngine.CreateScope(); scope.SetVariable("x", x); scope.SetVariable("y", y); source.Execute(scope); if (!scope.ContainsVariable("tile")) { throw new InvalidOperationException("Tile script does not set the 'tile' variable appropriately."); } return(scope.GetVariable("tile")); }
static void Main(string[] args) { Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString("print 'Hello World!'"); pythonScript.Execute(); }
/*-------------------------------------Network Thread------------------------------------------*/ /* ---------------------------------------WARNING----------------------------------------------*/ /* The code you are about to witness is a brainwave and if given more time it would be seperated * out into different functions and made more clear but I didn't have enough time */ public async Task NetworkThread() { await Task.Run(() => { try { while (true) { RestRequest request = new RestRequest("api/client/getclientlist"); IRestResponse resp = RestClient.Get(request); clientList = JsonConvert.DeserializeObject <List <Client> >(resp.Content); //Used to make the swarm more fair, start from the begginning and then start from the end if (fairSwarm) { fairSwarm = false; foreach (Client client in clientList) { if (me.port != client.port) { ChannelFactory <PeerServerInterface> channelFactory; NetTcpBinding tcp = new NetTcpBinding(); tcp.MaxReceivedMessageSize = 2147483647; string clientURL = String.Format("net.tcp://{0}:{1}/DataService", client.ipaddress, client.port); channelFactory = new ChannelFactory <PeerServerInterface>(tcp, clientURL); channel = channelFactory.CreateChannel(); currentJob = channel.DownloadJob(); if (currentJob != null) { byte[] hash = CreateHash(currentJob.code); if (hash.SequenceEqual(currentJob.hash)) { /*Sourced from * https://stackoverflow.com/questions/7053172/how-can-i-call-ironpython-code-from-a-c-sharp-app */ Job doJob = currentJob; if (string.IsNullOrEmpty(doJob.code)) { throw new EmptyCodeException(); } else { byte[] eoncodedBytes = Convert.FromBase64String(doJob.code); string code = System.Text.Encoding.UTF8.GetString(eoncodedBytes); ChangeUIElements(true); Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(code); var answer = pythonScript.Execute(); Dispatcher.BeginInvoke(new Action(() => { try { doJob.answer = answer; channel.UploadAns(doJob); jobCount++; ChangeJobCount(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) //Converting the answer to a string { doJob.answer = answer.ToString(); channel.UploadAns(doJob); jobCount++; ChangeJobCount(); } ChangeUIElements(false); Thread.Sleep(2000); //Just so it doesn't constantly keep checking it sleeps for 2 seconds to chill for a bit })); } currentJob = null; } } } } } else { fairSwarm = true; for (int i = clientList.Count - 1; i >= 0; i--) { Client client = clientList[i]; if (me.port != client.port) { ChannelFactory <PeerServerInterface> channelFactory; NetTcpBinding tcp = new NetTcpBinding(); tcp.MaxReceivedMessageSize = 2147483647; string clientURL = String.Format("net.tcp://{0}:{1}/DataService", client.ipaddress, client.port); channelFactory = new ChannelFactory <PeerServerInterface>(tcp, clientURL); channel = channelFactory.CreateChannel(); currentJob = channel.DownloadJob(); if (currentJob != null) { byte[] hash = CreateHash(currentJob.code); if (hash.SequenceEqual(currentJob.hash)) { /*Sourced from * https://stackoverflow.com/questions/7053172/how-can-i-call-ironpython-code-from-a-c-sharp-app */ Job doJob = currentJob; if (string.IsNullOrEmpty(doJob.code)) { throw new EmptyCodeException(); } byte[] eoncodedBytes = Convert.FromBase64String(doJob.code); string code = System.Text.Encoding.UTF8.GetString(eoncodedBytes); ChangeUIElements(true); Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine(); Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(code); var answer = pythonScript.Execute(); Dispatcher.BeginInvoke(new Action(() => { //If have time encode ans but who cares for now try { doJob.answer = answer; channel.UploadAns(doJob); jobCount++; ChangeJobCount(); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) //Converting the answer to a string { doJob.answer = answer.ToString(); channel.UploadAns(doJob); jobCount++; ChangeJobCount(); } ChangeUIElements(false); Thread.Sleep(5000); })); currentJob = null; } } } } } UpdateScore(); Thread.Sleep(10000); } } catch (System.ServiceModel.EndpointNotFoundException e) { //Occurs when someone leaves the swarm UpdateScore(); logger.LogFunc("Error occured in the Networking Thread, someone has left the swarm abruptly"); } catch (IronPython.Runtime.UnboundNameException e) { //When the input something not code MessageBox.Show("It appears were given a job that was in the wrong format"); ChangeUIElements(false); currentJob.error = true; channel.UploadAns(currentJob); logger.LogFunc("Error occured in the Networking Thread, the users input code is invalid"); } catch (EmptyCodeException e) { //when the input is empty logger.LogFunc("Error occured in the Networking Thread, the user didn't enter any code"); } }); }