Reload the current python script

There is a reload method in python to reload an imported module, but is there a way to reload the current script without restarting, this would be very helpful when debugging the script and modifying the code in real time while the script is running. In Visual Basic, I remember that this functionality was called "apply code changes", but I needed the same functionality as a function call such as "refresh ()" that would immediately apply the code changes.

This will run smoothly when the independent function in the script is changed, and we need to immediately apply the code change without restarting the script.

Turning on:

reload(self) 

      

Job?

+3


source to share


4 answers


reload(self)

won't work because it reload()

works with modules, not live class instances. What you want is some kind of logic external to your main application that checks to see if it needs to be reloaded. You should think about what is needed to re-create the application state after a reboot.

Some hints in this direction: Guido van Rossum once wrote: xreload.py ; it's a little more than reload()

you 'd need a loop that checks for changes every x seconds and applies that.



Also have a look at livecoding which basically does this. EDIT: I mistook this project for something else (which I haven't found now), sorry.

maybe this SO question will help you

+2


source


Perhaps you mean something like this:

import pdb
import importlib
from os.path import basename

def function():
    print("hello world")

if __name__ == "__main__":
    # import this module, but not as __main__ so everything other than this
    # if statement is executed
    mainmodname = basename(__file__)[:-3]
    module = importlib.import_module(mainmodname)

    while True:
        # reload the module to check for changes
        importlib.reload(module)
        # update the globals of __main__ with the any new or changed 
        # functions or classes in the reloaded module
        globals().update(vars(module))
        function()
        pdb.set_trace()

      



Run the code, then change the content function

and type c

at the prompt to start the next iteration of the loop.

0


source


test.py

class Test(object):

    def getTest(self):
       return 'test1'

      

testReload.py

from test import Test
t = Test()
print t.getTest()

# change return value (test.py)

import importlib
module = importlib.import_module(Test.__module__)
reload(module)
from test import Test
t = Test()
print t.getTest()

      

0


source


If you are working in an interactive session you can use ipython autoreload

autoreload reloads modules automatically before entering execution of the code entered at the IPython prompt.

Of course, this also works at the module level, so you would do something like:

>>>import myscript
>>>myscript.main()
*do some changes in myscript.py*
>>>myscript.main() #is now changed

      

-1


source