public object Execute(CompiledCode compiledCode, ScriptScope scope) { Debug.Assert(_executingThread == null); _executingThread = Thread.CurrentThread; try { object result = compiledCode.Execute(scope); Console.WriteLine(RemoteCommandDispatcher.OutputCompleteMarker); return result; } catch (ThreadAbortException tae) { KeyboardInterruptException pki = tae.ExceptionState as KeyboardInterruptException; if (pki != null) { // Most exceptions get propagated back to the client. However, ThreadAbortException is handled // differently by the remoting infrastructure, and gets wrapped in a RemotingException // ("An error occurred while processing the request on the server"). So we filter it out // and raise the KeyboardInterruptException Thread.ResetAbort(); throw pki; } else { throw; } } finally { _executingThread = null; } }
public override bool Init(IEnumerable<IFreeDocument> docus) { OneOutput = false; var source = engine.CreateScriptSourceFromString(Script); compiledCode = source.Compile(); IsMultiYield = ScriptWorkMode == ScriptWorkMode.文档列表; return true; }
internal static BuildResult GetBuildResult(string virtualPath, IBuildProvider buildProvider) { // If any script files in App_Scripts changed, they need to be reloaded ReloadChangedScriptFiles(); virtualPath = VirtualPathUtility.ToAbsolute(virtualPath); string cacheKey = virtualPath.ToLowerInvariant(); // Look up the cache before and after taking the lock BuildResult result = (BuildResult)HttpRuntime.Cache[cacheKey]; if (result != null) { return(result); } ScriptEngine scriptEngine = buildProvider.GetScriptEngine(); lock (typeof(EngineHelper)) { result = (BuildResult)HttpRuntime.Cache[cacheKey]; if (result != null) { return(result); } DateTime utcStart = DateTime.UtcNow; CompiledCode compiledCode = null; string scriptCode = buildProvider.GetScriptCode(); if (scriptCode != null) { // We pass the physical path for debugging purpose string physicalPath = HostingEnvironment.MapPath(virtualPath); ScriptSource source = scriptEngine.CreateScriptSourceFromString(scriptCode, physicalPath, SourceCodeKind.File); try { compiledCode = source.Compile(); } catch (SyntaxErrorException e) { EngineHelper.ThrowSyntaxErrorException(e); } } // Note that we cache the result even if there is no script, to avoid having to check // again later. result = buildProvider.CreateBuildResult(compiledCode, virtualPath); CacheDependency cacheDependency = HostingEnvironment.VirtualPathProvider.GetCacheDependency( virtualPath, new Util.SingleObjectCollection(virtualPath), utcStart); // Cache the result with a 5 minute sliding expiration HttpRuntime.Cache.Insert(cacheKey, result, cacheDependency, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5)); } return(result); }
public void LoadScript() { Scope.SetVariable("Stats", Stats); Scope.SetVariable("Balance", Balance); var source = Engine.CreateScriptSourceFromFile(FileName); CompCode = source.Compile(); dynamic result = CompCode.Execute(Scope); }
public override bool Init(IEnumerable<IFreeDocument> docus) { var text = File.ReadAllText("tn/tnpy.py",Encoding.UTF8); var source = engine.CreateScriptSourceFromString(text); compiledCode = source.Compile(); IsMultiYield = ScriptWorkMode == ScriptWorkMode.文档列表; return true; }
public override bool Init(IEnumerable <IFreeDocument> docus) { OneOutput = false; var source = engine.CreateScriptSourceFromString(Script); compiledCode = source.Compile(); IsMultiYield = ScriptWorkMode == ScriptWorkMode.文档列表; return(true); }
public void Compile_Statement_UnboundVar_Test() { ScriptScope scope = _runTime.CreateScope(); //Compile a statement referencing an unbound variable, which generates a runtime error CompiledCode e1 = _testEng.CreateScriptSourceFromString("print unbound+2", SourceCodeKind.Statements).Compile(); e1.Execute(scope); }
public void Compile_Expression_Basic1_Test() { ScriptScope scope = _runTime.CreateScope(); //Compile and execution a normal expression CompiledCode e1 = _testEng.CreateScriptSourceFromString("2+2").Compile(); TestHelpers.AssertOutput(_runTime, delegate() { e1.Execute(scope); }, ""); }
public override bool Init(IEnumerable <IFreeDocument> docus) { var text = File.ReadAllText("tn/tnpy.py", Encoding.UTF8); var source = engine.CreateScriptSourceFromString(text); compiledCode = source.Compile(); IsMultiYield = ScriptWorkMode == ScriptWorkMode.文档列表; return(true); }
public TResult RunFromString <TResult>(string code, string variableName) { ScriptSource source = _engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements); CompiledCode cc = source.Compile(); ScriptScope scope = _engine.CreateScope(); cc.Execute(scope); return(scope.GetVariable <TResult>(variableName)); }
public dynamic ExecuteScript(string code) { _source = _engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements); _compiled = _source.Compile(); dynamic result = _compiled.Execute(_scope); return(result); }
public object Execute(CompiledCode compiledCode, ScriptScope scope) { // Delegate the operation to the RemoteCommandDispatcher which will execute the code in the remote runtime object result = _remoteCommandDispatcher.Execute(compiledCode, scope); // Output is received async, and so we need explicit synchronization in the remote console _remoteOutputReceived.WaitOne(); return result; }
private void CompileSourceAndExecute(String code) { ScriptSource source = pyEngine.CreateScriptSourceFromString (code, SourceCodeKind.Statements); CompiledCode compiled = source.Compile(); // Executes in the scope of Python compiled.Execute(pyScope); }
/// <summary> /// Executes the script expression in compiled form. If the script hasn't been compiled yet, it is compiled before execution. The compilation /// results are reused when this <see cref="ExpressionScript{TResult}"/> is executed again. /// </summary> /// <returns>The result of running the script.</returns> public TResult Execute() { if (_compiledScript == null) { _compiledScript = _scriptSource.Compile(); } return(ScriptContext.Execute(() => _compiledScript.Execute <TResult> (_scriptEnvironment.ScriptScope))); }
public void Compile_Expression_UnboundVar_Test() { ScriptScope scope = _runTime.CreateScope(); //Compile an expression referencing an unbound variable, which generates a runtime error CompiledCode e1 = _testEng.CreateScriptSourceFromString("unbound + 2").Compile(); e1.Execute(scope); }
public PythonLoader(string code, string className = "PyClass") { //creating engine and stuff engine = Python.CreateEngine(); scope = engine.CreateScope(); //loading and compiling code source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements); compiled = source.Compile(); }
public PythonItem(ScriptEngine engine, ScriptScope scope, string name, CompiledCode code) { this.engine = engine; this.scope = scope; this.name = name; this.code = code; Header = name; PreviewMouseDown += PythonItem_MouseDown; }
public PythonLoader(string funcPrefix, string prefix, string code) : base(prefix) { this.funcPrefix = funcPrefix; engine = IronPython.Hosting.Python.CreateEngine(); scope = engine.CreateScope(); source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements); compiled = source.Compile(); compiled.Execute(scope); }
public object Execute(CompiledCode compiledCode, ScriptScope scope) { // Delegate the operation to the RemoteCommandDispatcher which will execute the code in the remote runtime object result = _remoteCommandDispatcher.Execute(compiledCode, scope); // Output is received async, and so we need explicit synchronization in the remote console _remoteOutputReceived.WaitOne(); return(result); }
public string GetResponse(string query) { string name = query.Substring(1, query.Length - 1); CompiledCode code = WebServer.digest.FindByName(name); if (code == null) { return(""); } return(code.minimalCode); }
public void Compile_Invoke() { string singleExp = _codeSnippets[CodeType.SimpleExpressionOnePlusOne]; int expectedResult = 2; ScriptSource source = _testEng.CreateScriptSourceFromString(singleExp, SourceCodeKind.Expression); CompiledCode ccode = source.Compile(); object result = ccode.Execute(); Assert.AreEqual(expectedResult, (int)result); }
public ScriptFilter(string scriptText) { Validation.CheckObject("scriptText", scriptText); //initialize python runtime = Python.CreateRuntime(); engine = Python.GetEngine(runtime); //load the script source = engine.CreateScriptSourceFromString(scriptText); script = source.Compile(); }
private static void initAsNeeded() { if (_runtime != null) { return; } BugFixer.Run(); DebugUtil.Trigger(); string langQName = typeof(IronPython.Runtime.PythonContext).AssemblyQualifiedName; var langSetup = new LanguageSetup(langQName, "IronPython", new string[] { "IronPython", "Python", "py" }, new string[] { ".py" }); var setup = new ScriptRuntimeSetup(); langSetup.ExceptionDetail = true; // options can be found in ironpython2-ipy-2.7.7\Languages\IronPython\IronPython\Runtime\PythonOptions.cs langSetup.Options["Optimize"] = false; langSetup.Options["StripDocStrings"] = false; langSetup.Options["Frames"] = true; langSetup.Options["Tracing"] = true; // setup.LanguageSetups.Add(langSetup); //this is responsible for python being able to access private members on CLR objects: setup.PrivateBinding = true; _runtime = new ScriptRuntime(setup); _engine = _runtime.GetEngine("IronPython"); //This works for the simple purpose of creating a __main__ module //inspect.stack() should work after doing this. //Not sure if there's a better way. //This solution is from: //https://stackoverflow.com/questions/8264596/how-do-i-set-name-to-main-when-using-ironpython-hosted var pco = (IronPython.Compiler.PythonCompilerOptions)_engine.GetCompilerOptions(); pco.ModuleName = "__main__"; pco.Module |= IronPython.Runtime.ModuleOptions.Initialize; var source = Engine.CreateScriptSourceFromString(@"'''This is the __main__ module'''"); CompiledCode compiled = source.Compile(pco); mainScope = CreateScope(); compiled.Execute(mainScope); //more options string[] searchpaths = new string[] { System.IO.Path.Combine(Util.ModBasePath, "IronPython-2.7.7/Lib/"), System.IO.Path.Combine(Util.ModBasePath, "PythonModules/") }; _engine.SetSearchPaths(searchpaths); _runtime.LoadAssembly(System.Reflection.Assembly.GetExecutingAssembly()); _runtime.LoadAssembly(typeof(Verse.Game).Assembly); }
public void Compile_Statement_Basic1_Test() { ScriptScope scope = _runTime.CreateScope(); scope.SetVariable("modulevar", 5); //Compile and execute a normal statement CompiledCode e1 = _testEng.CreateScriptSourceFromString("print 2+2", SourceCodeKind.Statements).Compile(); TestHelpers.AssertOutput(_runTime, delegate() { e1.Execute(scope); }, "4"); }
public void RunPY(string Path) { try { scriptSource = Engine.CreateScriptSourceFromFile(Path); compiledCode = scriptSource.Compile(); compiledCode.Execute(Scope); }catch (Exception ex) { } }
public PythonProgram GetProgram(String programName) { PythonProgram atual = programs[programName]; ScriptScope scope = engine.CreateScope(); ScriptSource source = atual.source; CompiledCode compiled = atual.compiled; PythonProgram pgm = new PythonProgram(programName, scope, source, compiled); return(pgm); }
public void Execute_NullScopeArgumentTest() { ScriptSource source = _testEng.CreateScriptSourceFromString( _codeSnippets[CodeType.SimpleExpressionOnePlusOne]); MyErrorListener errorListen = new MyErrorListener(); CompiledCode compiled = source.Compile(errorListen); Assert.IsTrue(errorListen._message == null); compiled.Execute((ScriptScope)null); }
internal static void ExecuteCompiledCode(CompiledCode compiledExpression, ScriptScope module) { try { compiledExpression.Execute(module); } catch (Exception e) { if (!ProcessRuntimeException(compiledExpression.Engine, e, null)) { throw; } } }
public void Compile_Statement_ModuleBoundVar_Test() { ScriptScope scope = _runTime.CreateScope(); scope.SetVariable("modulevar", 5); //Compile a statement referencing a module bound variable CompiledCode e1 = _testEng.CreateScriptSourceFromString("print modulevar+2", SourceCodeKind.Statements).Compile(); TestHelpers.AssertOutput(_runTime, delegate() { e1.Execute(scope); }, "7"); }
public void Compile_Statement_StatementBoundVar_Test() { ScriptScope scope = _runTime.CreateScope(); //Bind a module variable in a statement and then reference it _testEng.CreateScriptSourceFromString("pythonvar='This is a python variable'", SourceCodeKind.Statements).Execute(scope); CompiledCode e1 = _testEng.CreateScriptSourceFromString("print pythonvar", SourceCodeKind.Statements).Compile(); TestHelpers.AssertOutput(_runTime, delegate() { e1.Execute(scope); }, "This is a python variable"); Assert.IsTrue(scope.ContainsVariable("pythonvar"), "Bound variable isn't visible in the module dict"); }
public void Execute_GenericTypeCastSmokeTest() { ScriptSource source = _PYEng.CreateScriptSourceFromFile(TestHelpers.CreateTempSourceFile(_codeSnippets[CodeType.SimpleExpressionOnePlusOne], ".py")); MyErrorListener errorListen = new MyErrorListener(); CompiledCode compiled = source.Compile(errorListen); Assert.IsTrue(errorListen._message == null); // ScriptScope scope = _PYEng.CreateScope(); // double result = compiled.Execute<double>(scope); // Assert.AreEqual(result, (double)2); }
public void Execute_ReturnExpressionValueNoArgs() { ScriptSource source = _PYEng.CreateScriptSourceFromString("1+1"); MyErrorListener errorListen = new MyErrorListener(); CompiledCode compiled = source.Compile(errorListen); Assert.IsTrue(errorListen._message == null); object result = compiled.Execute(); Assert.AreEqual(result, (object)2); }
private static void GetCurrentThreadID(ScriptEngine engine, CompiledCode code) { ScriptScope scope = engine.CreateScope(); code.Execute(scope); var showThread = scope.GetVariable<Func<object, object>>("showThread"); Console.WriteLine("C# ThreadID: {0}", Thread.CurrentThread.ManagedThreadId); var pythodResult = showThread(string.Format("Host Thread ID: {0}", Thread.CurrentThread.ManagedThreadId)); Console.WriteLine(pythodResult); }
/// <summary> /// Compile and execute the source code within a file. /// </summary> /// <param name="filename">The path and filename of the file that contains the script.</param> /// <exception cref="System.ArgumentNullException">Source can not be null, python scope can not be null.</exception> public void CompileAndExecuteFile(string filename) { if (String.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } if (_pythonScope == null) { throw new ArgumentNullException("PythonScope"); } FileStream fileStream = null; StreamReader streamReader = null; string sourceCode = null; try { // Open the file stream. using (fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (streamReader = new StreamReader(fileStream)) { // Read all the script data in the file. sourceCode = streamReader.ReadToEnd(); // Close the streams. streamReader.Close(); fileStream.Close(); } // Compile the source code. ScriptSource source = _pythonEngine.CreateScriptSourceFromString(sourceCode, SourceCodeKind.Statements); CompiledCode compiled = source.Compile(); // Executes in the scope of Python compiled.Execute(_pythonScope); } catch (Exception) { throw; } finally { if (streamReader != null) { streamReader.Dispose(); } if (fileStream != null) { fileStream.Dispose(); } } }
public void CompileCodeFromClass(string code, string className) { //loading and compiling code Source = Engine.CreateScriptSourceFromString(code, 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)); }
public void Compile_Expression_ModuleBoundVar_Test() { ScriptScope scope = _runTime.CreateScope(); scope.SetVariable("modulevar", 5); //Compile an expression referencing a module bound variable CompiledCode e1 = _testEng.CreateScriptSourceFromString("modulevar+2").Compile(); TestHelpers.AssertOutput(_runTime, delegate() { e1.Execute(scope); }, ""); }
private static void GetCurrentThreadID(ScriptEngine engine, CompiledCode code) { ScriptScope scope = engine.CreateScope(); code.Execute(scope); var showThread = scope.GetVariable <Func <object, object> >("showThread"); Console.WriteLine("C# ThreadID: {0}", Thread.CurrentThread.ManagedThreadId); var pythodResult = showThread(string.Format("Host Thread ID: {0}", Thread.CurrentThread.ManagedThreadId)); Console.WriteLine(pythodResult); }
public object loadCode(string Path) { try { code = pyEngine.CreateScriptSourceFromFile(Path).Compile(); return true; } catch (Exception e) { return e; } }
public void Execute_ReturnExpressionValueForDefaultScopeArg() { ScriptSource source = _PYEng.CreateScriptSourceFromString("x=1+1", SourceCodeKind.Statements); MyErrorListener errorListen = new MyErrorListener(); CompiledCode compiled = source.Compile(errorListen); Assert.IsTrue(errorListen._message == null); compiled.Execute(); // ScriptScope scope = compiled.DefaultScope(); // object result = scope.GetVariable("x"); // Assert.AreEqual(result, (object)2); }
public pyDissector(string fileName) { engine = Python.CreateEngine(); scope = engine.CreateScope(); var runtime = engine.Runtime; runtime.LoadAssembly(typeof(PacketDotNet.Packet).Assembly); runtime.LoadAssembly(typeof(pyDissector).Assembly); src = engine.CreateScriptSourceFromFile(fileName); program = src.Compile(); var result = program.Execute(scope); var filterString = scope.GetVariable<string>("nativeFilterString"); myFilter = filterGen.genFilter(filterString); parseFunc = scope.GetVariable<Func<Packet, HLPacket>>("parsePacket"); }
public Engine(string filePath,Inventor.PlanarSketch oSketch,Inventor.Application oApp, double slotHeight, double slotWidth) { _engine = Python.CreateEngine(new Dictionary<string, object>() { {"Frames", true}, {"FullFrames", true}}); _runtime = _engine.Runtime; Assembly invAssembly = Assembly.LoadFile(@"C:\Windows\Microsoft.NET\assembly\GAC_MSIL\Autodesk.Inventor.Interop\v4.0_17.0.0.0__d84147f8b4276564\Autodesk.Inventor.interop.dll"); _runtime.LoadAssembly(invAssembly); _scope = _engine.CreateScope(); //Make variable names visible within the python file. These string names will be used an arguments in the python file. _scope.SetVariable("oPlanarSketch",oSketch); _scope.SetVariable("oApp",oApp); _scope.SetVariable("slotHeight",slotHeight); _scope.SetVariable("slotWidth",slotWidth); ScriptSource _script = _engine.CreateScriptSourceFromFile(filePath); _code = _script.Compile(); }
public PythonInstance(string code, string className = "PyClass") { //creating engine and stuff engine = Python.CreateEngine(); scope = engine.CreateScope(); //loading and compiling codes 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)); }
public Engine(string source) { _engine = Python.CreateEngine(); _runtime = _engine.Runtime; AddAssemblies(); PublishModule(); _scope = _engine.CreateScope(); _scope.SetVariable("__name__", "__main__"); Scope _main = HostingHelpers.GetScope(_scope); _runtime.Globals.SetVariable("__main__", _main); ScriptSource _script = _engine.CreateScriptSourceFromString(source, SourceCodeKind.Statements); _code = _script.Compile(); }
public PythonInstance(string className = "PyClass") { string code = @" import sys sys.path.append(r'C:\Program Files\IronPython 2.7\Lib') import os import hashlib import urllib2 class PyClass: def __init__(self): pass def somemethod(self): print 'in some method' def isodd(self, n): return 1 == n % 2 def get_hash(self,name): readsize = 64 * 1024 with open(name, 'rb') as f: size = os.path.getsize(name) data = f.read(readsize) f.seek(-readsize, os.SEEK_END) data += f.read(readsize) return hashlib.md5(data).hexdigest() "; //creating engine and stuff engine = Python.CreateEngine(); 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)); }
public override bool Deserialize(XElement xml) { this.Code = xml.Value; var options = new Dictionary<string, object>(); options["LightweightScopes"] = true; var engine = Python.CreateEngine(options); _runtime = engine.Runtime; try { var source = engine.CreateScriptSourceFromString(this.Code, SourceCodeKind.AutoDetect); _code = source.Compile(); } catch { // TODO: Log this return false; } return true; }
private void compileScript() { buildClear(); outputClear(); if (scriptEngine == null) { initializeEngine(); } Stopwatch stopwatch = Stopwatch.StartNew(); string code = codeText.Text; ScriptSource scriptSource = scriptEngine.CreateScriptSourceFromString(code); try { script = scriptSource.Compile(); offset = 0.0; startTicks = DateTime.UtcNow.Ticks; settings.Code = code; } catch (Exception ex) { buildError(ex.Message); } Func<object> factory = null; try { script.Execute(scriptScope); if (!scriptScope.TryGetVariable("Factory", out factory)) { factory = null; } } catch (Exception ex) { buildError(ex.Message); } if (factory != null) { try { scriptClass = factory(); } catch (Exception ex) { buildError(ex.Message); scriptClass = null; } } if (scriptClass != null) { try { Func<UInt32> sampleCount = scriptEngine.Operations.GetMember(scriptClass, "sampleCount"); UInt32 samples = sampleCount(); xValues = new double[samples]; yValues = new double[samples]; } catch (MissingMemberException) { if (xValues == null || yValues == null) { xValues = new double[200]; yValues = new double[200]; } } try { scriptCalculate = scriptEngine.Operations.GetMember(scriptClass, "calculate"); } catch (MissingMemberException) { scriptCalculate = null; } } if (scriptCalculate != null) { try { scriptCalculate(offset, xValues, yValues); settings.Code = code; plotTimer.Start(); } catch (Exception ex) { buildError(ex.Message); scriptCalculate = null; } } stopwatch.Stop(); double secs = (1000.0 * stopwatch.ElapsedTicks) / (double)(Stopwatch.Frequency); buildInfo(String.Format("Compiled in {0:f3}ms", secs)); }
public static void Shutdown() { if (watcher != null) { watcher = null; watcher.Changed -= watcher_Changed; watcher.EnableRaisingEvents = false; } source = null; compiledCode = null; rendererClass = null; rendererImpl = null; pyEngine = null; objOps = null; }
public static void Reload() { try { source = pyEngine.CreateScriptSourceFromFile(RendererPyPath); // Load the script compiledCode = source.Compile(); compiledCode.Execute(scope); // Create class object rendererClass = scope.GetVariable("Renderer"); // Retrieve the class object if (rendererClass != null) rendererImpl = objOps.Invoke(rendererClass) as IRenderer; // Create an instance of the Renderer } catch (Exception) { source = null; compiledCode = null; rendererClass = null; rendererImpl = null; } }
/// <summary> /// Initializes a new instance of the <see cref="ApplicationScript"/> class. /// </summary> /// <param name="path">The path.</param> /// <param name="code">The code.</param> /// <param name="scope">The scope.</param> internal ApplicationScript(string path, CompiledCode code, ScriptScope scope) { _Path = path; _code = code; _scope = scope; }
public object Execute(CompiledCode compiledCode, ScriptScope scope) { return compiledCode.Execute(scope); }
public Task<double> EvaluateCompiled(CompiledCode c) { return Task.Run(() => { try { object result = c.Execute(_scope); return (double)result; } catch (Exception ex) { MainWindow.ErrorDialog(ex.Message); return double.NaN; } }); }