How can you reload the CPython engine from python code

Hello!

Tiny question if someone know: how it is possible to call the “reinitialize CPython engine” (see image) this from python code script?

Many thanks in advance! :open_hands:

  1. Language Python 3.9.10 (mcneel.pythonnet.python) is not yet ready or failed initialization
    I have The same question

Hello @13555850710 ! Sorry, what do you mean by that? If you meant this issue, this is not what I mean. The Python interpreter is initizalizing correctly.

What I meant is how you can force the python interpreter’s reinitialization from code.

We have been working on this a bit.

Put this at the top of the script:

# flag: python.reloadEngine

That will reset the engine each time it runs. This can take some extra time to reload, but does allow libraries to be reloaded if those happen to be changing often.

4 Likes

Thank you @scottd ! That’s amazing .
Is there some documentation for these commands like flag:, r:, env: etc?
That would be great to know!

In the meanwhile as a solution to precisely targeting only the package I am working on I am doing this:

import sys
import importlib

packages_2_reload = ["name_of_the_pacakge1", "name_of_the_pacakge2"]
for package in packages_2_reload:
  for key in list(sys.modules.keys()):
      if package in key:
          importlib.reload(sys.modules[key])
1 Like

This is the guide that has some of the flags. And the one that will be updated soon I hope with the additional information:

We are also working on this one as we add more features:

2 Likes

@andrea.settimi Reloading pytohn modules is complicated. In the example that you shared, make sure to check the module spec and loader to only reload modules that are actually loaded from a file or directory. Otherwise .reload() method can throw an exception.

This is what Rhino does internally to collect reloadable modules:

BUILTIN_ORIGINS = ['built-in', 'frozen']

def get_reloadable_modules():
    reloadables = []

    for m in sys.modules.values():
        if inspect.ismodule(m):
            spec = getattr(m, "__spec__", None)
            if spec:
                if spec.origin in BUILTIN_ORIGINS \
                        or isinstance(spec.loader, SourcelessFileLoader):
                    continue
            
            reloadables.append(m)

    return reloadables

Rhino uses a complicated script to reload python modules internally. If you only want to reload the modules you are working on you can call .reload on your module only as well.

2 Likes