[Ironpython-users] scope get/set variable and invoking python function

Slide slide.o.mix at gmail.com
Thu Apr 5 06:43:42 CEST 2012


FYI, if you only want to READ the global variable, you don't need to
do what I said below, but to write to it, you have to "declare" it as
a global before writing to it inside the function.

On Wed, Apr 4, 2012 at 9:40 PM, Slide <slide.o.mix at gmail.com> wrote:
> The Test1 inside the function is not the same as the Test1 outside the
> function, you need to make the Test1 in the function a reference to
> the global Test1 for the scope. Try this
>
> def TestFunction()
>    global Test1
>    Test1 = 4
>
> On Wed, Apr 4, 2012 at 9:38 PM, Bill <bg271828 at gmail.com> wrote:
>> I am having a problem in ironpython 2.7.2.1 with executing a python
>> function that changes variables set in the scope via SetVariable. The
>> problem is these variables are never actually updated on the c# side
>> after the python function executes. Here is a couple different
>> examples, all of which don't work:
>>
>> The python code:
>>
>> def TestFunction():
>>    Test1 = 4
>>
>> The c# code:
>>
>> Example 1:
>>
>> ScriptEngine sEng = Python.CreateEngine();
>> ScriptScope scope;
>> dynamic fHand;
>>
>> scope = sEng.Runtime.CreateScope();
>>
>> scope.SetVariable("Test1", 0);
>>
>> fHand = sEng.ExecuteFile("c:\test.py"); // Contains python code listed above
>> if (scope.ContainsVariable("TestFunction"))
>>    fHand.TestFunction();
>>
>> int result = scope.GetVariable<int>("Test1"); // This is still set to
>> 0 when it should be set to 4 now.
>>
>> Example 2:
>>
>> ScriptScope scope = Python.CreateRuntime().UseFile("c:\test.py");
>> dynamic fHand = scope;
>> scope.SetVariable("Test1", 0);
>>
>> if (scope.ContainsVariable("TestFunction"))
>>    fHand.TestFunction();
>>
>> int result = scope.GetVariable<int>("Test1"); // This is still set to
>> 0 when it should be set to 4 now.
>>
>>
>> What am I missing here? Is it really that python functions cannot
>> update variables set in the scope? Python code outside of functions
>> are able to update them without any issues.
>> _______________________________________________
>> Ironpython-users mailing list
>> Ironpython-users at python.org
>> http://mail.python.org/mailman/listinfo/ironpython-users
>
>
>
> --
> Website: http://earl-of-code.com



-- 
Website: http://earl-of-code.com


More information about the Ironpython-users mailing list