private void StartPythonSouce(string filePath) { using (StreamReader sr = new StreamReader(filePath, System.Text.Encoding.UTF8)) { script = sr.ReadToEnd(); } scriptEngine = Python.CreateEngine(); // Pythonスクリプト実行エンジン scriptScope = scriptEngine.CreateScope(); // 実行エンジンに渡す値を設定する scriptSource = scriptEngine.CreateScriptSourceFromString(script); // Pythonのソースを設定 scriptSource.Execute(scriptScope); // ソースを実行する var Result = scriptScope.GetVariable <IronPython.Runtime.List>(ClosedList); stateList = Result.Cast <string>().ToList(); WalkingTheRobot(); }
public ScriptedUniverse(XmlNode scriptedNode) { string pythonFilePath = "", className = ""; XmlParser.ParseScriptedSrc(scriptedNode, ref pythonFilePath, ref className); var engine = Python.CreateEngine(); var scope = engine.CreateScope(); var ops = engine.Operations; var p = engine.GetSearchPaths(); p.Add(AppDomain.CurrentDomain.BaseDirectory + "\\..\\..\\..\\PythonScripting"); engine.SetSearchPaths(p); engine.ExecuteFile(pythonFilePath, scope); var pythonType = scope.GetVariable(className); _pythonInstance = ops.CreateInstance(pythonType, scriptedNode); }
private static string ExecutePython(string scriptContent, PythonModel model) { var engine = Python.CreateEngine(); var pc = HostingHelpers.GetLanguageContext(engine) as PythonContext; var hooks = pc?.SystemState.Get__dict__()["path_hooks"] as List; hooks?.Clear(); var searchPaths = engine.GetSearchPaths(); searchPaths.Add(ConfigurationManager.AppSettings["PythonLibPath"]); engine.SetSearchPaths(searchPaths); using (var ms = new MemoryStream()) using (var sw = new StreamWriter(ms)) { engine.Runtime.IO.SetOutput(ms, sw); engine.Runtime.IO.SetErrorOutput(ms, sw); try { var sc = engine.CreateScriptSourceFromString(scriptContent); var code = sc.Compile(); var scope = engine.CreateScope(); scope.SetVariable("model", model); scope.SetVariable("Data", model.Data); var qf = new QueryFunctions(model.db, model.dictionary); scope.SetVariable("q", qf); code.Execute(scope); ms.Position = 0; using (var sr = new StreamReader(ms)) { var s = sr.ReadToEnd(); return(s); } } catch (Exception ex) { var err = engine.GetService <ExceptionOperations>().FormatException(ex); throw new Exception(err); } } }
public void TestScopedPythonInterop() { ScriptEngine engine = Python.CreateEngine(); int age = 42; ScriptScope scope = engine.CreateScope(); scope.SetVariable("a", age); string expression = "1 < a < 50"; ScriptSource source = engine.CreateScriptSourceFromString(expression, SourceCodeKind.Expression); dynamic result = source.Execute(scope); Assert.IsTrue(result); }
public ScriptedSubsystem(string filePath, string className, Dependencies dependencies, Type collectorType) { Name = className; CollectorType = collectorType; var engine = Python.CreateEngine(); var scope = engine.CreateScope(); var ops = engine.Operations; engine.ExecuteFile(filePath, scope); var pythonType = scope.GetVariable(className); PythonInstance = ops.CreateInstance(pythonType); Dictionary <string, Delegate> newDependencies = PythonInstance.getDependencyDictionary(); dependencies.Append(newDependencies); SubsystemDependencyFunctions = PythonInstance.getDependencyDictionary(); }
public void InitializeFromString(string script) { Engine = Python.CreateEngine(); Source = Engine.CreateScriptSourceFromString(script, SourceCodeKind.Statements); try { Compiled = Source.Compile(); } catch (SyntaxErrorException see) { var eo = Engine.GetService <ExceptionOperations>(); LastError = eo.FormatException(see); throw; } Scope = Engine.CreateScope(); Operations = Engine.Operations; }
public PyScriptTask(int id, string name, Station station) : base(id, name, station) { _scriptEngine = Python.CreateEngine(); var paths = _scriptEngine.GetSearchPaths(); paths.Add(@"C:\Program Files\IronPython 2.7\Lib"); _scriptEngine.SetSearchPaths(paths); _scriptEngine.Runtime.LoadAssembly(Assembly.GetAssembly(typeof(RunningState))); _scriptEngine.Runtime.LoadAssembly(Assembly.GetAssembly(typeof(MotionExtensionEx))); _scriptEngine.Runtime.LoadAssembly(Assembly.GetAssembly(typeof(StationTaskExtension))); _scriptScope = _scriptEngine.CreateScope(); _scriptScope.SetVariable("t", this); ScriptFileName = $@".\Scripts\{Name}.py"; }
public static string PatchParameter(string parameter, int serviceid) { var engine = Python.CreateEngine(); // Extract Python language engine from their grasp var scope = engine.CreateScope(); // Introduce Python namespace (scope) var d = new Dictionary <string, object> { { "serviceid", serviceid }, { "parameter", parameter } }; // Add some sample parameters. Notice that there is no need in specifically setting the object type, interpreter will do that part for us in the script properly with high probability scope.SetVariable("params", d); // This will be the name of the dictionary in python script, initialized with previously created .NET Dictionary ScriptSource source = engine.CreateScriptSourceFromFile(@"C:\Users\User\Desktop\Project\next_mole_server\next_mole_server\script.py"); // Load the script object result = source.Execute(scope); parameter = scope.GetVariable <string>("parameter"); // To get the finally set variable 'parameter' from the python script return(parameter); }
static void Main(string[] args) { string PyCode = ""; if (args.Length >= 1) { switch (args[0].Split(':')[0].ToLower()) { case "--b64script": { byte[] ScriptBytes = Convert.FromBase64String(args[0].Split(':')[1]); PyCode = Encoding.ASCII.GetString(ScriptBytes); break; } case "--script": { PyCode = args[0].Split(':')[1]; break; } default: { PrintUsage(); return; } } } else { PrintUsage(); return; } ScriptEngine engine = Python.CreateEngine(); Assembly ass = Assembly.GetExecutingAssembly(); var sysScope = engine.GetSysModule(); var importer = new ResourceMetaPathImporter(Assembly.GetExecutingAssembly(), "Lib.zip"); List metaPath = (List)sysScope.GetVariable("meta_path"); metaPath.Add(importer); sysScope.SetVariable("meta_path", metaPath); var script = engine.CreateScriptSourceFromString(PyCode, SourceCodeKind.Statements); script.Execute(); Console.WriteLine("Finished Executing."); }
/// <summary> /// Constructor of the <see cref="PythonScriptPanelViewModel"/> /// </summary> /// <param name="panelTitle">The title of the panel associated to this view model.</param> /// <param name="scriptingProxy">A <see cref="IScriptingProxy"/> object to perform the script commands associated to CDP4.</param> /// <param name="openSessions">The list of the open <see cref="ISession"/>.</param> public PythonScriptPanelViewModel(string panelTitle, IScriptingProxy scriptingProxy, ReactiveList <ISession> openSessions) : base(panelTitle, scriptingProxy, "*.py", openSessions, true) { this.LoadHighlightingSheet(PythonHighlighting); this.Engine = Python.CreateEngine(); this.Engine.Runtime.LoadAssembly(typeof(string).Assembly); this.Engine.Runtime.LoadAssembly(typeof(Uri).Assembly); var searchPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var paths = this.Engine.GetSearchPaths(); paths.Add(searchPath); this.Engine.SetSearchPaths(paths); this.Scope = this.Engine.CreateScope(); this.Scope.SetVariable(Command, this.ScriptingProxy); }
static void Main(string[] args) { var scriptEngine = Python.CreateEngine(); var scriptScope = scriptEngine.CreateScope(); string code = @"def AddFunc(a, b): print 'AddFunc called' return (a + b) "; scriptEngine.Execute(code, scriptScope); dynamic addFunc = scriptScope.GetVariable("AddFunc"); int nResult = addFunc(5, 10); Console.WriteLine(nResult); }
public FromImportStatement ParseStatement(string text) { ScriptEngine engine = Python.CreateEngine(); PythonContext context = HostingHelpers.GetLanguageContext(engine) as PythonContext; StringTextContentProvider textProvider = new StringTextContentProvider(text); SourceUnit source = context.CreateSourceUnit(textProvider, String.Empty, SourceCodeKind.SingleStatement); PythonCompilerSink sink = new PythonCompilerSink(); CompilerContext compilerContext = new CompilerContext(source, new PythonCompilerOptions(), sink); PythonOptions options = new PythonOptions(); using (Parser parser = Parser.CreateParser(compilerContext, options)) { return(parser.ParseSingleStatement().Body as FromImportStatement); } }
public static int Main(string[] args) { var files = new List <string>(); var config = new Config(); config.ParseArgs(args); if (!config.Validate()) { ConsoleOps.Usage(true); } // we don't use the engine, but we create it so we can have a default context. ScriptEngine engine = Python.CreateEngine(config.PythonOptions); ConsoleOps.Info($"IronPython Compiler for {engine.Setup.DisplayName} ({engine.LanguageVersion})"); ConsoleOps.Info($"{config}"); ConsoleOps.Info("compiling..."); var compileOptions = new Dictionary <string, object>() { { "mainModule", config.MainName }, { "assemblyFileVersion", config.FileVersion }, { "copyright", config.Copyright }, { "productName", config.ProductName }, { "productVersion", config.ProductVersion }, }; try { ClrModule.CompileModules(DefaultContext.DefaultCLS, Path.Combine(config.OutputPath, Path.ChangeExtension(config.Output, ".dll")), compileOptions, config.Files.ToArray()); var outputfilename = Path.Combine(config.OutputPath, Path.ChangeExtension(config.Output, ".dll")); if (config.Target != PEFileKinds.Dll) { outputfilename = Path.Combine(config.OutputPath, Path.ChangeExtension(config.Output, ".exe")); GenerateExe(config); } ConsoleOps.Info($"Saved to {outputfilename}"); } catch (Exception e) { Console.WriteLine(); ConsoleOps.Error(true, e.Message); } return(0); }
/// <summary> /// Constructor /// </summary> /// <param name="searchPaths">Search paths to python lib</param> public PythonScripting(List <string> searchPaths = null) { _sources = new Dictionary <string, ScriptSource>(); _engine = Python.CreateEngine(); if (searchPaths != null && searchPaths.Count > 0) { ICollection <string> paths = _engine.GetSearchPaths(); foreach (string path in searchPaths) { paths.Add(path); } _engine.SetSearchPaths(paths); } }
public string Login(Person p) { var script = Db.Content("API-LoginInfo"); if (script == null) { script = new Content(); script.Body = @" from System import * from System.Text import * class LoginInfo(object): def Run(self, m, w, p): w.Start('Login') w.Attr('PeopleId', p.PeopleId) w.Attr('PreferredName', p.PreferredName) w.Attr('Last', p.LastName) w.Attr('EmailAddress', p.EmailAddress) w.Attr('IsMember', p.MemberStatusId == 10) for b in m.StatusFlags(p.PeopleId): w.Add('StatusFlag', b); w.End() return w.ToString() "; } var engine = Python.CreateEngine(); var sc = engine.CreateScriptSourceFromString(script.Body); try { var code = sc.Compile(); var scope = engine.CreateScope(); code.Execute(scope); dynamic LoginInfo = scope.GetVariable("LoginInfo"); dynamic m = LoginInfo(); var api = new APIFunctions(Db); var w = new APIWriter(); return(m.Run(api, w, p)); } catch (Exception ex) { return($"<login error=\"API-LoginInfo script error: {ex.Message}\" />"); } }
public void CreateData(int flag, out dynamic fun, out dynamic Low, out dynamic Up, out dynamic step, out dynamic N) { //Класс ScriptEngine применяется для создания движка, выполняющего скрипт. //Объект ScriptScope позволяет взаимодействовать со скриптом, получая или устанавливая его переменные, получая ссылки на функции. ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); //В вычислительном модуле python используется модуль random.py //он находится в IronPython.StdLib //для работы программы необходимо подключить папку с StdLib: var paths = engine.GetSearchPaths(); //путь к папке paths.Add(@"D:\IronPython.StdLib.2.7.5\content\Lib"); engine.SetSearchPaths(paths); string str_fun = "x**2"; if (flag == 1) { ServerConsole.Print("Подынтегральная функция:" + str_fun); } int Temp_Low = 1; int Temp_Up = 10; int Temp_step = (Int32)((Temp_Up - Temp_Low) / 2); int Temp_N = 10000; scope.SetVariable("fun", str_fun); scope.SetVariable("Low", Temp_Low); scope.SetVariable("Up", Temp_Up); scope.SetVariable("step", Temp_step); scope.SetVariable("N", Temp_N); //непосредственный запуск модуля engine.ExecuteFile("D://monte-carlo.py", scope); //теперь можно "разобрать" запущенный скрипт на части, вытаскивая из него необходимые функции и переменные fun = scope.GetVariable("fun"); Low = scope.GetVariable("Low"); Up = scope.GetVariable("Up"); step = scope.GetVariable("step"); N = scope.GetVariable("N"); }
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 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 static void Main(string[] args) { Console.WriteLine("Hello World!"); ScriptEngine pyEngine = Python.CreateEngine(); ScriptScope pyScope = pyEngine.CreateScope(); pyScope.SetVariable("test", "test me"); string code = @" print 'test = ' + test class MyClass: def __init__(self): pass def somemethod(self): print 'in some method' def isodd(self, n): return 1 == n % 2 "; ScriptSource source = pyEngine.CreateScriptSourceFromString(code); CompiledCode compiled = source.Compile(); compiled.Execute(pyScope); // Get the Python Class object MyClass = pyEngine.Operations.Invoke(pyScope.GetVariable("MyClass")); // Invoke a method of the class pyEngine.Operations.InvokeMember(MyClass, "somemethod", new object[0]); // create a callable function to 'somemethod' Action SomeMethod2 = pyEngine.Operations.GetMember & lt; Action> (MyClass, "somemethod"); SomeMethod2(); // create a callable function to 'isodd' Func< int, bool> IsOdd = pyEngine.Operations.GetMember & lt; Func< int, bool> > (MyClass, "isodd"); Console.WriteLine(IsOdd(1).ToString()); Console.WriteLine(IsOdd(2).ToString()); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
public void ExecuteWithOutput() { var projects = new Mock <ILinkScriptsToProjects>(); using (var writer = new ScriptOutputPipe()) { var output = string.Empty; writer.OnScriptOutput += (s, e) => output += e.Text; var engine = Python.CreateEngine(); var runner = new RemoteScriptRunner(projects.Object, writer, engine); var script = "print \"Hello\""; runner.Execute(script, new CancelScriptToken()); Assert.AreEqual("Hello" + Environment.NewLine, output); } }
private void commit_Click(object sender, EventArgs e) { try { this.result.AppendText("=====================欢迎使用黑狗自动化娱乐软件!=====================\r\n"); ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); ScriptSource script = engine.CreateScriptSourceFromFile(@"F:\VisualStudio2015\Projects\blackdog\blackdog\Script.py"); var dates = script.Execute(scope); this.result.AppendText("program is over!!"); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static ScriptEngine CreateEngine(TestOptions options) { var engine = Python.CreateEngine(new Dictionary <string, object> { { "Debug", options.Debug }, { "Frames", options.Frames || options.FullFrames }, { "FullFrames", options.FullFrames }, { "RecursionLimit", options.MaxRecursion }, { "Tracing", options.Tracing } }); engine.SetHostVariables( Path.GetDirectoryName(Executable), Executable, ""); AddSearchPaths(engine); return(engine); }
private ScriptEngine CreateIronPythonEngine() { var options = new Dictionary <string, object>(); options["Debug"] = true; var engine = Python.CreateEngine(options); var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies(); // Add all TaleWorlds.* assemblies to the engine so that they are accessible // Otherwise you would need to use clr.AddReference foreach (var twAssembly in AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.StartsWith("TaleWorlds"))) { engine.Runtime.LoadAssembly(twAssembly); } engine.Runtime.LoadAssembly(typeof(IPythonModule).Assembly); return(engine); }
/// <summary> /// Python engine initialization /// </summary> /// <param name="options"></param> /// <returns></returns> public static ScriptEngine CreateEngine(IDictionary <string, object> options = null) { var engine = Python.CreateEngine(options); engine.IncludeNativeLibrary(); var infoStream = new MemoryStream(); var infoWriter = new PythonPrinter(Debug.Log, infoStream); engine.Runtime.IO.SetOutput(infoStream, infoWriter); var errorStream = new MemoryStream(); var errorWriter = new PythonPrinter(Debug.LogError, errorStream); engine.Runtime.IO.SetErrorOutput(errorStream, errorWriter); return(engine); }
static void Main(string[] args) { Console.WriteLine("Running python in C# application."); ScriptEngine engine = Python.CreateEngine(); string inputText = String.Empty; while (true) { Console.Write(">>>"); inputText = Console.ReadLine(); if (inputText == "exit()") { break; } var outputText = engine.Execute(inputText); Console.WriteLine(outputText.ToString()); } }
// Use this for initialization void Start() { var engine = Python.CreateEngine(); ICollection <string> searchPaths = engine.GetSearchPaths(); //Path to the folder of greeter.py searchPaths.Add(Application.dataPath); //Path to the Python standard library searchPaths.Add(Application.dataPath + @"\Plugins\Lib\"); engine.SetSearchPaths(searchPaths); dynamic py = engine.ExecuteFile(Application.dataPath + @"\greeter.py"); dynamic greeter = py.Greeter("Mika"); Debug.Log(greeter.greet()); Debug.Log(greeter.random_number(1, 5)); }
public PythonInstance(string code, string className = "PyClass") { //creating engine and stuff engine = Python.CreateEngine(); engine.Runtime.LoadAssembly(typeof(UnityEngine.GameObject).Assembly); scope = engine.CreateScope(); //loading and compiling code source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements); compiled = source.Compile(); //now executing this code (the code should contain a class) compiled.Execute(scope); //now creating an object that could be used to access the stuff inside a python script pythonClass = engine.Operations.Invoke(scope.GetVariable(className)); }
private dynamic RunPythonHelper(object linq, string code) { #if !NETSTANDARD2_1 var tEngine = Python.CreateEngine(); var tScope = tEngine.CreateScope(); tScope.SetVariable("linq", linq); var tSource = tEngine.CreateScriptSourceFromString(code.Trim(), SourceCodeKind.Statements); var tCompiled = tSource.Compile(); tCompiled.Execute(tScope); return(tScope.GetVariable("result")); #else Assert.Ignore("Iron python doesn't support .net 2.0 core"); return(new object()); #endif }
// See: // * python_paths.md in Configuration folder // * BRefLeagueBattingController.cs // * BRefLeagueBattingController.py // Status [July 3, 2019]: // * If all you want are simple variables, then this work // * It breaks if you need to bring things in like numpy or pandas // * Check all links / notes listed at top of this file // * IronPython doesn't work with Python3 yet; Python 2.7 will be deprecated in 2020 // * Probably best to wait until IronPython is upgraded to support Python3 before doing any more on this #region CONNECT TO PYTHON ------------------------------------------------------------ // STATUS: this works /// <summary> /// Create a connection between .NET and a Python file; This must be run before any of the other methods will work /// </summary> /// <param name="fileName">todo: describe fileName parameter on ConnectToPythonFile</param> /// <remarks> /// This must be run before any of the other below methods /// </remarks> /// <returns> /// A connection between .NET and Python /// </returns> public object ConnectToPythonFile(string fileName) { // * Extract Python language engine from their grasp // * Microsoft.Scripting.Hosting.ScriptEngine ScriptEngine engine = Python.CreateEngine(); // * Introduce Python namespace (scope) // * Microsoft.Scripting.Hosting.ScriptScope ScriptScope scope = engine.CreateScope(); // * Microsoft.Scripting.Hosting.ScriptSource ScriptSource source = engine.CreateScriptSourceFromFile(fileName); // * Any other functions must be called after this object connectionToPython = source.Execute(scope); return(scope); }
private void button1_Click(object sender, EventArgs e) { try { ScriptEngine pyEngine = Python.CreateEngine(); //创建Python解释器对象 dynamic py = pyEngine.ExecuteFile(@"test1.py"); //读取脚本文件 string dd = py.main(textBox1.Lines); //调用脚本文件中对应的函数 textBox2.Text += dd + "\r\n"; //ScriptEngine pyEngine = Python.CreateEngine();//创建一个Python引擎 //dynamic da = pyEngine.CreateScriptSourceFromString(textBox1.Text);//读取脚本源码字符串 //da.Execute();//执行脚本;winForm程序中执行结果会在输出中显示;控制台程序中执行结果会显示在控制台中 } catch (Exception ex) { textBox2.Text += ex.Message; } }