[IronPython] Embedding IronPython

Michael Foord fuzzyman at voidspace.org.uk
Tue Dec 30 23:04:53 CET 2008


Hello Josh,

Sorry for the delayed reply - life is hectic at the moment and I'm still 
copy editing IronPython in Action.

I've copied your email to the IronPython list as I don't know whether 
the CreateScope and other methods of the ScriptEngine are thread safe. 
My instinct would be to say no, but on the other hand the DLR has to 
handle running multi-threaded code so maybe...

Michael Foord

greenbergjosh at hotmail.com wrote:
> Some one has sent you a message via your contact form. They filled in the
> following values :
>
> comment = I read your article on IronPython and I was hoping you might have an answer to the following question.
>
> I would like to embed IronPython in a web application.  I would like to initialize the engine and runtime in the Application_Start() method and store an instance of the ScriptEngine in the Application object.  Then, any time I need to run some python I intend to call the ScriptEngine::CreateScope() method and use it to get a new scope in which to execute my code.  Is this approach thread safe?  I will have only one instance of the ScriptEngine shared by many threads.  Each thread will call CreateScope whenever it chooses.
>
>  
>
> It will look something like:
>
>  
>
> protected void Application_Start(object sender, EventArgs e)
>
> {
>
> ScriptRuntime truntime = ScriptRuntime.Create();
>
> ScriptEngine teng = truntime.GetEngine("py");
>
> this.Application.Add(“PythonEngine”, teng);
>
> }
>
>  
>
> Then, in some web page or dll called by a web page I would do
>
>  
>
> ..
>
> ScriptEngine se = (ScriptEngine)Application[“PythonEngine”];
>
> ScriptScope ss = se.CreateScope();
>
> ScriptSource src = se.CreateScriptSourceFromString(“y=24”, SourceCodeKind.Statements);
>
> CompiledCode cc = src.Compile();
>
> cc.Execute(scope);
>
> ...
>
>  
>
> Is this going to work or will I run into threading problems?  In other words, is the ScriptEngine thread-safe?  Will it serialize all of my cc.Execute() calls?  Any other insight into its behavior in this regard would be appreciated.
>
>  
>
> Many Thanks,
>
> Josh
>
> name = Josh
> email = greenbergjosh at hotmail.com
> subject = Embedding IronPython
>   


-- 
http://www.ironpythoninaction.com/
http://www.voidspace.org.uk/blog





More information about the Ironpython-users mailing list