The following code, using the Python.NET component to execute a Python script, can be executed successfully.
However, the script engine is not closed. Here is a demonstration of the operation.
Where should this line of code be placed? I'm stuck!
PythonEngine.Shutdown();
Thanks in advance for any suggestions and help.
However, the script engine is not closed. Here is a demonstration of the operation.
Where should this line of code be placed? I'm stuck!
PythonEngine.Shutdown();
Thanks in advance for any suggestions and help.
// script "PythonNET_Test.cs"
/*/ r %dll%\PyNet\Python.Runtime.dll /*/
using System;
using Python.Runtime;
class Program
{
public static void Main()
{
Person someone = new Person();
someone.FirstName = "John";
someone.LastName = "Doe";
someone.Age = 21;
object age = PythonInterop.RunPythonCodeAndReturn(@"
someone.Age=someone.Age+3;
hisAge=someone.Age
", someone, "someone", "hisAge");
Console.WriteLine("His age has changed to: " + age.ToString());
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
public class PythonInterop
{
public static void Initialize()
{
string pythonDll = @"C:\Users\YourUserNameHere\AppData\Local\Programs\Python\Python38\python38.dll";
Environment.SetEnvironmentVariable("PYTHONNET_PYDLL", pythonDll);
PythonEngine.Initialize();
}
public static object RunPythonCodeAndReturn(string pycode, object parameter, string parameterName, string returnedVariableName)
{
object returnedVariable = new object();
Initialize();
using (Py.GIL())
{
using (var scope = Py.CreateScope())
{
scope.Set(parameterName, parameter.ToPython());
scope.Exec(pycode);
returnedVariable = scope.Get<object>(returnedVariableName);
return returnedVariable;
}
}
PythonEngine.Shutdown();
}
}
}