static void Main(string[] args) { try { ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null); ScriptRuntime runtime = new ScriptRuntime(setup); ScriptEngine engine = Python.GetEngine(runtime); var paths = engine.GetSearchPaths(); paths.Add(@"C:\Program Files\IronPython 2.7\lib"); engine.SetSearchPaths(paths); ScriptSource source = engine.CreateScriptSourceFromFile(@"D:\VsCodeDemo\pythonfile\EagleXml.py"); ScriptScope scope = engine.CreateScope(); List <String> argv = new List <String>(); //Do some stuff and fill argv argv.Add("."); argv.Add(@"D:\VsCodeDemo\pythonfile\MEHOW-0.xml"); engine.GetSysModule().SetVariable("argv", argv); source.Execute(scope); } catch (Exception e) { Console.WriteLine(e.Message); } Console.Read(); }
/// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA) { var path = @"C:\Users\darthoma\Documents\GitHub\honey-badger\examples\helloworld\helloworld.py"; var runtimeSetup = Python.CreateRuntimeSetup((IDictionary <string, object>)null); runtimeSetup.Options.Add("DivisionOptions", (object)PythonDivisionOptions.New); runtimeSetup.Options.Add("Frames", (object)true); runtimeSetup.Options.Add("Tracing", (object)true); ScriptRuntime scriptRuntime = new ScriptRuntime(runtimeSetup); scriptRuntime.LoadAssembly(typeof(RhinoApp).Assembly); scriptRuntime.LoadAssembly(typeof(int).Assembly); scriptRuntime.LoadAssembly(typeof(Form).Assembly); scriptRuntime.LoadAssembly(typeof(Color).Assembly); scriptRuntime.LoadAssembly(typeof(LengthExtension).Assembly); var engine = scriptRuntime.GetEngine("py"); var stream = new hbtestStdioStream(); scriptRuntime.IO.SetErrorOutput((Stream)stream, Encoding.Default); scriptRuntime.IO.SetOutput((Stream)stream, Encoding.Default); scriptRuntime.IO.SetInput((Stream)stream, Encoding.Default); ScriptScope scope = engine.CreateScope(); ScriptSource scriptSourceFromFile = engine.CreateScriptSourceFromFile( path, Encoding.Default, SourceCodeKind.Statements); scriptSourceFromFile.Execute(scope); var main = scope.GetVariable("main"); var result = main("hello, world"); RhinoApp.WriteLine($"executed: {result}"); }
private PythonExec() { setup = Python.CreateRuntimeSetup(null); runtime = new ScriptRuntime(setup); engine = Python.GetEngine(runtime); programs = new Dictionary <string, PythonProgram>(); }
// https://mail.python.org/pipermail/ironpython-users/2012-December/016366.html // http://ironpython.net/blog/2012/07/07/whats-new-in-ironpython-273.html // https://blog.adamfurmanek.pl/2017/10/14/sqlxd-part-22/ public static dynamic CreateEngine() { ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(GetRuntimeOptions()); var pyRuntime = new ScriptRuntime(setup); ScriptEngine engineInstance = Python.GetEngine(pyRuntime); AddPythonLibrariesToSysMetaPath(engineInstance); return(engineInstance); }
protected override ScriptEngine MakeEngine(Stream stream, TextWriter writer, TextReader reader) { _factory.SetConsoleOut(writer); _factory.SetConsoleError(writer); _factory.SetConsoleIn(reader); var runtime = (ScriptRuntime)_factory.CreateRuntime(Python.CreateRuntimeSetup(GetOptions())); var res = runtime.GetEngine("Python"); InitializeEngine(stream, writer, res); return(res); }
// https://mail.python.org/pipermail/ironpython-users/2012-December/016366.html // http://ironpython.net/blog/2012/07/07/whats-new-in-ironpython-273.html // https://blog.adamfurmanek.pl/2017/10/14/sqlxd-part-22/ public static dynamic CreateEngine() { ScriptRuntimeSetup setup = Python.CreateRuntimeSetup( new Dictionary <string, object> { ["Debug"] = false }); var pyRuntime = new ScriptRuntime(setup); ScriptEngine engineInstance = Python.GetEngine(pyRuntime); AddPythonLibrariesToSysMetaPath(engineInstance); return(engineInstance); }
private (string, string, string, string) GetParam(int serviceid, string path) { string Question = "", Answer = "", Boxes = "", Hints = ""; int RandInt = rand.Next(1000); ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null); ScriptRuntime runtime = new ScriptRuntime(setup); var engine = Python.GetEngine(runtime); var paths = engine.GetSearchPaths(); paths.Add(@"C:\Python27\Lib"); engine.SetSearchPaths(paths); ScriptSource source = engine.CreateScriptSourceFromFile(path); var scope = engine.CreateScope(); var d = new Dictionary <string, object> { { "serviceid", serviceid }, { "question", Question }, { "answer", Answer }, { "ansName", Boxes }, { "prompt", Hints } }; scope.SetVariable("params", d); scope.SetVariable("seed", RandInt); object result = source.Execute(scope); Question = scope.GetVariable <string>("question"); Answer = scope.GetVariable <string>("answer"); try { Boxes = scope.GetVariable <string>("ansName"); } catch { Boxes = ""; } try { Hints = scope.GetVariable <string>("prompt"); } catch { Hints = ""; } return(Question, Answer, Boxes, Hints); }
static void Main(string[] args) { ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null); ScriptRuntime runtime = new ScriptRuntime(setup); ScriptEngine engine = Python.GetEngine(runtime); ScriptSource source = engine.CreateScriptSourceFromFile("HelloWorld.py"); ScriptScope scope = engine.CreateScope(); List <String> argv = new List <String>(); //Do some stuff and fill argv argv.Add("foo"); argv.Add("bar"); engine.GetSysModule().SetVariable("argv", argv); source.Execute(scope); }
public void SaveStatistics() { //Run the python file #region ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null); ScriptRuntime runtime = new ScriptRuntime(setup); ScriptEngine engine = Python.GetEngine(runtime); ScriptSource source = engine.CreateScriptSourceFromFile("savestats.py"); ScriptScope scope = engine.CreateScope(); List <String> argv = new List <String>(); #endregion argv.Add(HareWins.ToString()); argv.Add(TurtleWins.ToString()); argv.Add(Draws.ToString()); engine.GetSysModule().SetVariable("argv", argv); source.Execute(scope); }
public async Task <IEnumerable <Course> > GetList(int?userId, string name, ContextSession session, bool includeDeleted = false) { var entity = GetEntities(session, includeDeleted).AsQueryable(); var courses = await entity.Where(obj => obj.Id > 0).ToListAsync(); SaveToCsv <Course>(courses, Environment.CurrentDirectory + "/csv/course.csv"); var ratings = _dbContext.Set <CourseRating>().AsQueryable(); if (!includeDeleted) { ratings = ratings.Where(obj => !obj.IsDeleted); } var i = await ratings.Where(obj => obj.Id > 0).ToListAsync(); SaveToCsv <CourseRating>(i, Environment.CurrentDirectory + "/csv/ratings_Final.csv"); ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null); ScriptRuntime runtime = new ScriptRuntime(setup); ScriptEngine engine = Python.GetEngine(runtime); ICollection <string> searchPaths = engine.GetSearchPaths(); searchPaths.Add("C:\\Users\\Admin\\PycharmProjects\\ArClassifier\\venv\\Lib"); searchPaths.Add("C:\\Users\\Admin\\PycharmProjects\\ArClassifier\\venv\\Lib\\site-packages"); engine.SetSearchPaths(searchPaths); ScriptSource source = engine.CreateScriptSourceFromFile(Environment.CurrentDirectory + "/CB_RS.py"); ScriptScope scope = engine.CreateScope(); List <String> argv = new List <String>(); argv.Add(session.UserId.ToString()); argv.Add(Environment.CurrentDirectory + "/csv/course.csv"); argv.Add(Environment.CurrentDirectory + "/csv/ratings_Final.csv"); engine.GetSysModule().SetVariable("argv", argv); try { var qq = source.Execute(scope); var qq2 = qq; } catch (Exception ex) { var error = ex; } return(await entity.Where(obj => obj.Id > 0).ToListAsync()); }
static void Main(string[] args) { var runtimeSetup = Python.CreateRuntimeSetup(new Dictionary <string, object>()); runtimeSetup.DebugMode = true; var runtime = new ScriptRuntime(runtimeSetup); var scope = runtime.CreateScope(new Dictionary <string, object> { { "name", "Batman" } }); var engine = runtime.GetEngine("py"); var scriptSource = engine.CreateScriptSourceFromFile("script.py"); var compiledCode = scriptSource.Compile(); compiledCode.Execute(scope); }
/// <summary> /// Create new runtime setup /// </summary> /// <returns></returns> public ScriptRuntimeSetup CreateRuntime() { var runtimeSetup = Python.CreateRuntimeSetup(null); runtimeSetup.DebugMode = true; runtimeSetup.Options["Frames"] = true; runtimeSetup.Options["FullFrames"] = true; if (LanguageOptionSet != null && runtimeSetup.LanguageSetups.Count > 0) { foreach (var opt in LanguageOptionSet) { runtimeSetup.LanguageSetups[0].Options[opt.Key] = opt.Value; } } return(runtimeSetup); }
protected void SetupEngine() { var setup = Python.CreateRuntimeSetup(null); setup.HostType = typeof(SnekScriptHost); var runtime = new ScriptRuntime(setup); engine = runtime.GetEngineByTypeName(typeof(PythonContext).AssemblyQualifiedName); SnekImporter.OverrideImport(engine); defaultScope = new SnekScope(engine.CreateScope()); SetupAssemblies(); AddSearchPath(Application.streamingAssetsPath + "/"); MlfProcessorManager.OnEngineInit(this); }
public void IronPython_3rdPartyLibUsage() { // Arrange var setup = Python.CreateRuntimeSetup(null); var runtime = new ScriptRuntime(setup); var engine = Python.GetEngine(runtime); var paths = engine.GetSearchPaths(); paths.Add(@"Lib\"); paths.Add(@"IronPythonTests\Modules\"); engine.SetSearchPaths(paths); // Act var source = engine.CreateScriptSourceFromFile(@"IronPythonTests\use_3rd_party_lib.py"); var scope = engine.CreateScope(); source.Execute(scope); var result = scope.GetVariable("result"); Assert.Equal(result, 200); }
public void IronPython_StdLibUsage() { // Arrange var setup = Python.CreateRuntimeSetup(null); var runtime = new ScriptRuntime(setup); var engine = Python.GetEngine(runtime); var paths = engine.GetSearchPaths(); paths.Add(@"Lib\"); engine.SetSearchPaths(paths); // Act var source = engine.CreateScriptSourceFromFile(@"IronPythonTests\use_stdlib.py"); var scope = engine.CreateScope(); source.Execute(scope); var result = scope.GetVariable("result"); // Assert Assert.Equal("{\"a\": 0, \"b\": 0, \"c\": 0}", result); }
public void Scenario_RemoteScriptFactory() { using (var factory = RemotePythonEvaluator.CreateFactory()) { var runtime = (ScriptRuntime)factory.CreateRuntime(Python.CreateRuntimeSetup(new Dictionary <string, object>())); StringWriter writer = new StringWriter(); StringWriter errWriter = new StringWriter(); runtime.IO.SetOutput(Stream.Null, writer); factory.SetConsoleOut(writer); factory.SetConsoleError(errWriter); // verify print goes to the correct output var engine = runtime.GetEngine("Python"); engine.Execute("print 'hello'"); var builder = writer.GetStringBuilder(); AreEqual(builder.ToString(), "hello\r\n"); builder.Clear(); // verify Console.WriteLine is redirected engine.Execute("import System\nSystem.Console.WriteLine('hello')\n"); AreEqual(builder.ToString(), "hello\r\n"); builder.Clear(); // verify Console.Error.WriteLine is redirected to stderr var errBuilder = errWriter.GetStringBuilder(); engine.Execute("import System\nSystem.Console.Error.WriteLine('hello')\n"); AreEqual(errBuilder.ToString(), "hello\r\n"); errBuilder.Clear(); // raise an exception, should be propagated back try { engine.Execute("import System\nraise System.ArgumentException()\n"); AreEqual(true, false); } catch (ArgumentException) { } /* * // verify that all code runs on the same thread * var scope = engine.CreateScope(); * engine.Execute("import System"); * * * List<object> res = new List<object>(); * for (int i = 0; i < 100; i++) { * ThreadPool.QueueUserWorkItem( * (x) => { * object value = engine.Execute("System.Threading.Thread.CurrentThread.ManagedThreadId", scope); * lock (res) { * res.Add(value); * } * }); * } * * while (res.Count != 100) { * Thread.Sleep(100); * } * * for (int i = 1; i < res.Count; i++) { * if (!res[i - 1].Equals(res[i])) { * throw new Exception("running on multiple threads"); * } * }*/ // create a long running work item, execute it, and then make sure we can continue to execute work items. ThreadPool.QueueUserWorkItem(x => { engine.Execute("while True: pass"); }); Thread.Sleep(1000); factory.Abort(); AreEqual(engine.Execute("42"), 42); } // check starting on an MTA thread using (var factory = new RemoteScriptFactory(ApartmentState.MTA)) { var runtime = (ScriptRuntime)factory.CreateRuntime(Python.CreateRuntimeSetup(new Dictionary <string, object>())); var engine = runtime.GetEngine("Python"); AreEqual(engine.Execute("import System\nSystem.Threading.Thread.CurrentThread.ApartmentState == System.Threading.ApartmentState.MTA"), true); } // check starting on an STA thread using (var factory = new RemoteScriptFactory(ApartmentState.STA)) { var runtime = (ScriptRuntime)factory.CreateRuntime(Python.CreateRuntimeSetup(new Dictionary <string, object>())); var engine = runtime.GetEngine("Python"); AreEqual(engine.Execute("import System\nSystem.Threading.Thread.CurrentThread.ApartmentState == System.Threading.ApartmentState.STA"), true); } }