Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Close the Python.NET script engine
#1
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.

[Image: close.gif]
Where should this line of code be placed? I'm stuck! Shy
PythonEngine.Shutdown(); 

Thanks in advance for any suggestions and help.
 
Code:
Copy      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(); 
        }
    }
}


Messages In This Thread
Close the Python.NET script engine - by Davider - 08-04-2023, 11:18 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)