/// <summary> /// Run the Python code specified, passing a parameter to it from C# and receiving a return value /// </summary> /// <param name="pycode">Specifies a block of Python code to run.</param> /// <param name="parameter">Specifies the parameter value.</param> /// <param name="parameterName">Specifies the parameter name within the Python code.</param> /// <param name="returnedVariableName">Specifies the name of the return value in the Python code.</param> /// <returns>The Python return value is returned.</returns> public object RunPythonCodeAndReturn(string pycode, object parameter, string parameterName, string returnedVariableName) { object returnedVariable = new object(); using (Py.GIL()) { using (PyModule scope = Py.CreateScope()) { scope.Set(parameterName, parameter.ToPython()); scope.Exec(pycode); returnedVariable = scope.Get <object>(returnedVariableName); } } return(returnedVariable); }
/// <summary> /// Run the Python code specified, passing a set of parameters to it from C# and receiving a return value /// </summary> /// <param name="pycode">Specifies a block of Python code to run.</param> /// <param name="returnedVariableName">Specifies the name of the return value in the Python code.</param> /// <param name="rgArg">Specifies a list of parameter name, value pairs.</param> /// <returns>The Python return value is returned.</returns> public object RunPythonCodeAndReturn(string pycode, string returnedVariableName, params KeyValuePair <string, object>[] rgArg) { object returnedVariable = new object(); using (Py.GIL()) { using (PyModule scope = Py.CreateScope()) { foreach (KeyValuePair <string, object> arg in rgArg) { scope.Set(arg.Key, arg.Value.ToPython()); } scope.Exec(pycode); returnedVariable = scope.Get <object>(returnedVariableName); } } return(returnedVariable); }
public void TestExec() { using (Py.GIL()) { ps.Set("bb", 100); //declare a global variable ps.Set("cc", 10); //declare a local variable ps.Exec("aa = bb + cc + 3"); var result = ps.Get <int>("aa"); Assert.AreEqual(113, result); } }