INTODAN
INTODAN

Reputation: 629

Unity + Pythonnet: Interpreter preserves state between plays, and only resets when the unity editor closes

I am trying to integrate python into my unity project using the nuget package pythonnet. I set my python lifecycle the same way it was set in this git project: https://github.com/shiena/Unity-PythonNet/blob/main/Assets/Scripts/PythonLifeCycle.cs

During runtime, I import a module like so:

        using (Py.GIL())
        {
            using (PyModule scope = Py.CreateScope())
            {
                dynamic sys = scope.Import("sys");
                Debug.Log(sys.modules.keys());
                sys.path.append("C:\\Users\\<user>\\my-package");
                dynamic pythonPackage = scope.Import("my_package");

                sys.path.append(packagePath);
                scope.Import("src");
                this.module = scope.Import("src.main");
            }
        }

When I exit and reenter play mode, and print sys.modules right after initializing the python engine and before I import the module again, I still see my_package in the global sys.modules (proves that using a scope doesn't help).

I tried:

The only thing that resets the sys.modules, is restarting the unity editor.

Is there any way to reset the sys.modules everytime I enter/exit playmode?

Thanks!

Update: I tried one additional thing: While going through pythonnet's code, I found a RestoreRuntimeData function. I removed all references to it, the problem still presists.

Upvotes: 1

Views: 23

Answers (1)

LOST
LOST

Reputation: 3269

I'm not sure what your goal is, but I suspect it can be achived by well-supported importlib.reload.

Upvotes: 0

Related Questions