private void button3_Click(object sender, EventArgs e) { try { var strExpression = @" import sys sys.stdout=my print 'ABC' "; var engine = Python.CreateEngine(); var scope = engine.CreateScope(); var sourceCode = engine.CreateScriptSourceFromString(strExpression); scope.SetVariable("my", this); var actual = sourceCode.Execute(scope); textBox1.Text += actual; } catch (System.Exception ex) { MessageBox.Show(ex.ToString()); } }
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(); totalState = stateList.Count; WalkingTheRobot(); }
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 Load(string file) { var source = File.ReadAllText(file); ScriptEngine engine = Python.CreateEngine(); engine.SetSearchPaths(new string[] { Path.Combine(_basePath, "ironpython", "lib") }); ScriptSource script = engine.CreateScriptSourceFromString(source); _pythonFunc = script.Execute() as PythonFunction; if (_pythonFunc == null) { throw new InvalidOperationException("The Python code must evaluate to a Python lambda expression that takes one parameter, e.g. `lambda x: x + 1`."); } _operations = engine.CreateOperations(); }
public void Load(string Path) { engine = Python.CreateEngine(); var functions = new List <RegionGenerator>(); var files = Directory.GetFiles(Path, "*.py", SearchOption.AllDirectories); foreach (string file in files) { try { functions.Add(new RegionGenerator(engine, File.ReadAllText(file))); }catch { Debug.Log("Error while loading script " + file); } } this.functions = functions.ToArray(); }
private static void Main(string[] args) { ScriptEngine engine = Python.CreateEngine(); engine.Runtime.LoadAssembly(Assembly.LoadFile(@"path_to.dll")); // note how scope is created var scope = engine.Runtime.ImportModule("test"); // how class type is grabbed var customerType = scope.GetVariable("Customer"); // how class is created using constructor with name (note dynamic keyword also) dynamic customer = engine.Operations.CreateInstance(customerType, "Customer Name"); // calling method on dynamic object var balance = customer.deposit(10.0m); // this outputs 10, as it should Console.WriteLine(balance); Console.ReadKey(); }
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 Shotgun() { lock (this) { if (_pythonModule == null) { // Find out where our files are Assembly exAssembly = System.Reflection.Assembly.GetExecutingAssembly(); Uri uriCodeBase = new Uri(exAssembly.CodeBase); String installBase = Path.GetDirectoryName(uriCodeBase.LocalPath.ToString()); // Initialize IronPython ScriptRuntime ipy = Python.CreateRuntime(); IronPython.Runtime.List path = ipy.GetSysModule().GetVariable("path"); // Point IronPython to our files path.append(Path.Combine(installBase, "Python", "PythonStatic.zip")); _pythonModule = ipy.UseFile(Path.Combine(installBase, "Python", "shotgun_config.py")); } } }
public PythonEvaluator() { var options = new Dictionary <string, object> { ["DivisionOptions"] = PythonDivisionOptions.New }; _errorWriter = new EventRaisingTextWriter(); _consoleWriter = new EventRaisingTextWriter(); _consoleWriter.StreamWritten += _consoleWriter_StreamWritten; _errorWriter.StreamWritten += _errorWriter_StreamWritten; _stream = new MemoryStream(); _engine = Python.CreateEngine(options); _engine.Runtime.IO.SetOutput(_stream, _consoleWriter); _engine.Runtime.IO.SetErrorOutput(_stream, _errorWriter); _scope = _engine.CreateScope(); }
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); }
public PythonEnvironment() { m_pythonEngine = Python.CreateEngine(); //Load the unity assembly so that python has access to basic unity types (GameObject, Vector3 etc) m_pythonEngine.Runtime.LoadAssembly(typeof(UnityEngine.Vector3).Assembly); //Load the executing assembly (current project's code) so python has access to your custom types m_pythonEngine.Runtime.LoadAssembly(System.Reflection.Assembly.GetExecutingAssembly()); m_scriptScope = m_pythonEngine.CreateScope(); var libs = new[] { "C:\\Program Files (x86)\\IronPython-2.7.7\\Lib", "C:\\Program Files (x86)\\IronPython-2.7.7\\DLLs", "C:\\Program Files (x86)\\IronPython-2.7.7", "C:\\Program Files (x86)\\IronPython-2.7.7\\lib\\site-packages" }; m_pythonEngine.SetSearchPaths(libs); }
static void Main(string[] args) { ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); engine.Execute("print 'hello, world'"); //engine.ExecuteFile("../../hello.py"); engine.ExecuteFile("../../factorial.py", scope); dynamic function = scope.GetVariable("factorial"); dynamic result = function(11); Console.WriteLine(result); Console.ReadLine(); }
/// <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); }
public PythonEngine(ClientHandler client) { this.client = client; Instance = this; _engine = Python.CreateEngine(); _scope = _engine.CreateScope(); _cachedObjects = new ObjectStorage(client); _gameAPI = new GameAPI(client, _scope); _engineAPI = new EngineAPI(client); PrepareStaticLocals(); var outputStream = new MemoryStream(); var outputStreamWriter = new TcpStreamWriter(outputStream, client); _engine.Runtime.IO.SetOutput(outputStream, outputStreamWriter); }
public static void test5() { try { ScriptEngine engine = Python.CreateEngine(); var paths = engine.GetSearchPaths(); paths.Add(@"D:\Program Files (x86)\IronPython 2.7\Lib"); engine.SetSearchPaths(paths); ScriptScope scope = engine.CreateScope(); ScriptSource script = engine.CreateScriptSourceFromFile(@"main.py"); var result = script.Execute(scope); } catch (Exception e) { Console.WriteLine(e.Message); } }
public static dynamic GetConfigValue(string name, string pypath = "configuration.py") { pypath = @"\\192.168.3.32\softwareTools\Autorivet_team_manage\settings\" + pypath; ScriptEngine engine = null; engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); if (File.Exists(pypath)) { engine.ExecuteFile(pypath, scope); return(scope.GetVariable(name)); } else { return(@"\\192.168.3.32\Autorivet\prepare\INFO\"); } }
private dynamic RunPythonHelper(object linq, string code) { #if !NETCOREAPP2_0 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 }
public Demo() { // Create IronPython var engine = Python.CreateEngine(); var script = engine.CreateScriptSourceFromString(PythonScript.Code); // Configure the engine with types var typesYouWantPythonToHaveAccessTo = new[] { typeof(IMessenger), typeof(IConfig) }; var typeExtractor = new ExtractTypesFromScript(engine); var exports = typeExtractor.GetPartsFromScript(script, typesYouWantPythonToHaveAccessTo); // Compose with MEF var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog); var batch = new CompositionBatch(exports, new ComposablePart[] { }); container.Compose(batch); container.SatisfyImportsOnce(this); }
// Update is called once per frame void Update() { if (t) { t = false; var engine = Python.CreateEngine(); ICollection <string> searchPaths = engine.GetSearchPaths(); searchPaths.Add(Application.dataPath); searchPaths.Add(Application.dataPath + @"/Plugins/Lib/"); engine.SetSearchPaths(searchPaths); dynamic py = engine.ExecuteFile(Application.dataPath + @"/playgtts.py"); dynamic speak = py.Speak(); speak.doSpeak("測試測試測試"); UnityEngine.Debug.Log("Done"); } }
private static string ExecutePython(string scriptContent, PythonModel model) { var engine = Python.CreateEngine(); // var libs = new [] // { // @"E:\GitHub\bvcms\CmsWeb\Lib" // }; // engine.SetSearchPaths(libs); 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 PyScript() { engine = Python.CreateEngine(); scope = engine.CreateScope(); AddPath("script"); string initCode = @" import sys class h2module: def setmodule(self, modname, fieldname, obj): if not sys.modules.get(modname): sys.modules[modname] = h2module() mod = __import__(modname) setattr(mod, fieldname, obj) sys.modules['h2ext'] = h2module() import h2ext FuncCache={} #import StringIO #import traceback def h2call(funcname, args): #try: global FuncCache;f = FuncCache.get(funcname); if f==None: mod2func = funcname.split('.') mod = __import__(mod2func[0]) f = getattr(mod, mod2func[1]) if not f: raise 'h2exception:' + '%s not found'%(funcname) FuncCache[funcname] = f return f(*args) #except Exception: #fp = StringIO.StringIO() #traceback.print_exc()#traceback.print_exc(file = fp) #msg = ''#fp.getvalue() #tracebackdata = 'h2exception:' + funcname + ' ' + msg #print(tracebackdata) #return tracebackdata #return None "; EvalStr(initCode); m_h2call = scope.GetVariable("h2call"); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // Get application and document objects UIApplication ui_app = commandData.Application; UIDocument ui_doc = ui_app?.ActiveUIDocument; Document doc = ui_doc?.Document; try { ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); scope.SetVariable("doc", doc); scope.SetVariable("uidoc", ui_doc); //engine.ExecuteFile("C:/Drive/ARMOPlug/ScriptPy/test.py", scope); string scriptName = Assembly.GetExecutingAssembly().GetName().Name + ".Resources." + "ALength.py"; Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(scriptName); if (stream != null) { string script = new StreamReader(stream).ReadToEnd(); engine.Execute(script, scope); } // Implement Selection Filter to select curves // Measure their total length // Return a message window that displays total length to user // Assuming that everything went right return Result.Succeeded return(Result.Succeeded); } // This is where we "catch" potential errors and define how to deal with them catch (Autodesk.Revit.Exceptions.OperationCanceledException) { // If user decided to cancel the operation return Result.Canceled return(Result.Cancelled); } catch (Exception ex) { // If something went wrong return Result.Failed message = ex.Message; return(Result.Failed); } }
public Engine(bool forTesting) { Log.DebugFormat("Creating scripting engine: forTesting={0}", forTesting); AppDomain sandbox = CreateSandbox(forTesting); _engine = Python.CreateEngine(sandbox); _outputWriter = new StreamWriter(_outputStream); _engine.Runtime.IO.SetOutput(_outputStream, _outputWriter); _engine.SetSearchPaths(new[] { Path.Combine(sandbox.BaseDirectory, @"Scripting\Lib") }); _api = new ScriptApi(this); var workingDirectory = Directory.GetCurrentDirectory(); Log.DebugFormat("Setting working directory: {0}", workingDirectory); if (Program.GameEngine != null) { workingDirectory = Path.Combine(Prefs.DataDirectory, "GameDatabase", Program.GameEngine.Definition.Id.ToString()); var search = _engine.GetSearchPaths(); search.Add(workingDirectory); _engine.SetSearchPaths(search); Program.GameEngine.EventProxy = new GameEventProxy(this); Program.GameEngine.ScriptEngine = this; } ActionsScope = CreateScope(workingDirectory); if (Program.GameEngine == null || forTesting) { return; } Log.Debug("Loading Scripts..."); foreach (var script in Program.GameEngine.Definition.GetScripts().ToArray()) { Log.DebugFormat("Loading Script {0}", script.Path); var src = _engine.CreateScriptSourceFromString(script.Script, SourceCodeKind.Statements); src.Execute(ActionsScope); Log.DebugFormat("Script Loaded"); } Log.Debug("Scripts Loaded."); //foreach (ScriptSource src in Program.GameEngine.Definition.GetScripts().Select( // s => _engine.CreateScriptSourceFromString(s.Script, SourceCodeKind.Statements))) //{ // src.Execute(ActionsScope); //} }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { // Get application and document objects UIApplication ui_app = commandData.Application; UIDocument ui_doc = ui_app?.ActiveUIDocument; Document doc = ui_doc?.Document; try { ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope(); scope.SetVariable("doc", doc); scope.SetVariable("uidoc", ui_doc); engine.ExecuteFile("D:/Testara.py", scope); //string DetailLinesLength = Assembly.GetExecutingAssembly().GetName().Name + ".Resources." + "SpreadEvenly.py"; //Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(DetailLinesLength); //if (stream != null) //{ // string script = new StreamReader(stream).ReadToEnd(); // engine.Execute(script, scope); //} return(Result.Succeeded); } // This is where we "catch" potential errors and define how to deal with them catch (Autodesk.Revit.Exceptions.OperationCanceledException) { // If user decided to cancel the operation return Result.Canceled return(Result.Cancelled); } catch (Exception ex) { // If something went wrong return Result.Failed message = ex.Message; return(Result.Failed); } }
public PythonExecutionEngine(string source, string className = "PyModule") { if (string.IsNullOrEmpty(source)) { throw new ArgumentException("script"); } string[] requiredAssemblies = new string[] { System.IO.Path.Combine(Environment.CurrentDirectory, "OpenTK.dll"), System.IO.Path.Combine(Environment.CurrentDirectory, "Duality.dll"), System.IO.Path.Combine(Environment.CurrentDirectory, "DualityPrimitives.dll") }; // Add reference to Duality binaries var builder = new System.Text.StringBuilder(); builder.AppendLine("import sys"); builder.AppendLine("import clr"); builder.AppendLine(); foreach (string assembly in requiredAssemblies) { builder.AppendLine(string.Format("clr.AddReferenceToFileAndPath(r\"{0}\")", assembly)); } builder.AppendLine(); string script = source.Insert(0, builder.ToString()); _engine = Python.CreateEngine(); _engine = Python.CreateEngine(); _engine.Runtime.IO.RedirectToConsole(); // for now we have to redirect to console // Setup stdlib path var searchPaths = _engine.GetSearchPaths(); searchPaths.Add(System.IO.Path.Combine(Environment.CurrentDirectory, "Lib")); _engine.SetSearchPaths(searchPaths); _scope = _engine.CreateScope(); _source = _engine.CreateScriptSourceFromString(script); _code = _source.Compile(); _code.Execute(_scope); _class = _engine.Operations.Invoke(_scope.GetVariable(className)); }
// Choose the file with the time domain data and the file to write the fft data to, then call the python script to perform the fft, then reads the data to a variable private void FFTButton_Click(object sender, EventArgs e) { DialogResult dr = openFileDialog2.ShowDialog(); if (dr == DialogResult.OK) { foreach (String path in openFileDialog2.FileNames) { filename = path; } } else { MessageBox.Show("Data not Recieved"); } dr = openFileDialog3.ShowDialog(); if (dr == DialogResult.OK) { foreach (String path in openFileDialog3.FileNames) { dataSelect2 = path; } MessageBox.Show("Path Chosen"); } else { MessageBox.Show("path not chosen"); } var ipy = Python.CreateRuntime(); dynamic test = ipy.UseFile("FFT.py"); test.DoFFT(filename, dataSelect2); MessageBox.Show("FFT complete, Reading Data"); readData(dataSelect2); FFTplot.Enabled = true; MessageBox.Show("Data Read"); /* * run_cmd("C:\\Python34\\cmd.exe", "python FFTscript.py " + dataSelect + " " + dataSelect2); * MessageBox.Show("FFT complete"); */ }
/// <summary> /// 初始化 /// </summary> /// <param name="pythonRuntimePath">运行时相对路径</param> /// <param name="pythonLibPath">自带类库路径</param> /// <param name="options"></param> public static void Initialize(string pythonRuntimePath, string pythonLibPath, Dictionary <string, object> options) { try { RuntimePath = (pythonRuntimePath ?? "").Replace(@"\", "/"); LibPath = pythonLibPath; _pyEngine = options == null || options.Count == 0 ? Python.CreateEngine() : Python.CreateEngine(options); _pyRuntime = _pyEngine.Runtime; SetPythonSearchPath(RuntimePath); RuntimePathWatcher(RuntimePath, true); } catch (Exception ex) { TraceLog.WriteError("PythonScriptHost Initialize path:{0} error:{1}", pythonRuntimePath, ex); } }
private static void Main() { Console.WriteLine("What would you like to print from python?"); var input = Console.ReadLine(); var py = Python.CreateEngine(); try { py.Execute("print('From Python: " + input + "')"); } catch (Exception ex) { Console.WriteLine("Oops! We couldn't print your message because of an exception: " + ex.Message); } Console.WriteLine("Press enter to exit..."); Console.ReadLine(); }
/// <summary> /// /// </summary> /// <param name="code"></param> /// <param name="bindingNames"></param> /// <param name="bindingValues"></param> /// <returns></returns> public static object EvaluateIronPythonScript( string code, IList bindingNames, [ArbitraryDimensionArrayImport] IList bindingValues) { var engine = Python.CreateEngine(); var scope = engine.CreateScope(); var amt = Math.Min(bindingNames.Count, bindingValues.Count); for (int i = 0; i < amt; i++) { scope.SetVariable((string)bindingNames[i], bindingValues[i]); } engine.CreateScriptSourceFromString(code).Execute(scope); return(scope.ContainsVariable("OUT") ? scope.GetVariable("OUT") : null); }
public void VerifyScripts() { XmlSerializer serializer = new XmlSerializer(typeof(game)); var fs = File.Open(Directory.GetFiles().First(x => x.Name == "definition.xml").FullName, FileMode.Open); var game = (game)serializer.Deserialize(fs); fs.Close(); var engine = Python.CreateEngine(AppDomain.CurrentDomain); var errorList = new List <string>(); foreach (var script in game.scripts) { var scr = script; var ss = engine.CreateScriptSourceFromFile(Path.Combine(Directory.FullName, scr.src)); ss.Compile(new CompileErrorListener((source, message, span, code, severity) => { var errString = String.Format( "[{0} {1}-{2}:{3} to {4}:{5}] {6} - {7}", severity.ToString(), code, span.Start.Line, span.Start.Column, span.End.Line, span.End.Column, scr.src, message); errorList.Add(errString); })); } var sb = new StringBuilder("==Script Errors=="); foreach (var err in errorList) { sb.AppendLine(err); } if (errorList.Count > 0) { throw new UserMessageException(sb.ToString()); } }