Another way to do this is to create a ScriptSource which is of kind Statements:
ScriptRuntime sr = ScriptRuntime.Create();
ScriptEngine engine = sr.GetEngine("py");
ScriptSource source =
engine.CreateScriptSourceFromFile("test.py", Encoding.Default,
SourceCodeKind.Statements);
ScriptScope scope = engine.CreateScope();
scope.SetVariable("__name__", "__main__");
source.Execute(scope);
The issue here is that when you create source which is of type File we
automatically set __name__ and __file__ - just like Python would if you
executed a module. Given that the scope and code are decoupled from each other
there's no way for us to set it in the scope until the code runs - and of
course the code runs after your SetVariable call. Unless there's some reason
using Statements is too onerous I'm inclined to say this is the correct
behavior.
Alternately we could check and see if __name__ / __file__ are already set and
then not set them. But I'm worried that would lead to some surprising behavior
when re-using scopes. I'm am open to suggestions though :).
-----Original Message-----
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Christian
Muirhead
Sent: Friday, June 20, 2008 7:17 AM
To: Discussion of IronPython
Subject: Re: [IronPython] upgrading to ip 2b3 in Resolver One
Christian Muirhead wrote:
> * Another thing I saw here was that you can't set __name__ in a scope
> when running a script loaded from a source file - that is, this:
>
> ScriptSource source = engine.CreateScriptSourceFromFile("test.py");
> ScriptScope scope = e.CreateScope();
> scope.SetVariable("__name__", "__main__");
> source.Execute(scope);
>
> when test.py contains
>
> print __name__
>
>
> prints "test"
Oh, I forgot to say - I got around this using source.ExecuteProgram,
where __name__ is set correctly.
--
Christian Muirhead
Resolver Systems
[EMAIL PROTECTED]
We're hiring! http://www.resolversystems.com/jobs/
Resolver Systems Ltd
17a Clerkenwell Road, London EC1M 5RD, UK
VAT No.: GB 893 5643 79 Registered in England and Wales as company
number 5467329.
Registered address: 843 Finchley Road, London NW11 8NA, UK
_______________________________________________
Users mailing list
[email protected]
http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
_______________________________________________
Users mailing list
[email protected]
http://lists.ironpython.com/listinfo.cgi/users-ironpython.com