简体   繁体   中英

Programmatically check for and disable IPython autoreload extension

I have a function that uses the Python importlib package to dynamically reload modules which generates some errors when the user is running the code from IPython and has the autoreload extension loaded and automatic reloading turned on (ie %autoreload 2 ). What I would like to do is have my code detect whether the user is running IPython, has the extension loaded, and has it set for automatic reloading. If so, disable it, run my block of code, then re-enable it.

I believe I can use the following code to detect whether we are in IPython and run magic functions, but I cannot figure out how to programmatically check whether autoreload has been loaded and whether %autoreload 2 is set.

from IPython import get_ipython

ipy = get_ipython()
if not ipy is None:
    # Need to check for %autoreload 2 here
    ipy.magic("%autoreload 0")
    # Run some code
    ipy.magic("%autoreload 2")

After reviewing the autoreload source code it appears that the following should work

from IPython import get_ipython
ipy = get_ipython()
if not ipy is None:
    if 'autoreload' in sys.modules:
        check_all = ipy.magics_manager.magics['line']['autoreload'].__self__._reloader.check_all
        enabled = ipy.magics_manager.magics['line']['autoreload'].__self__._reloader.enabled

        parameter = 0
        if check_all is False and enabled is True:
            parameter = 1
        elif check_all is True and enabled is True:
            parameter = 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM