Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload my Python source file, when interactively interpreting it with "python -i"

Tags:

python

When writing or debugging a Python program, I really like using the -i command line switch to be able to directly inspect my functions without having to run everything from start to finish.

However, whenever I make a change to the code I have to close and restart my interactive session, losing all temporary variables that I might have defined. How do I reload my source file from within the python interpreter?


The builtin function reload looks like it was made for this, but I can only use it with named modules:

>> import my_prog
>> print my_prog.x
-- prints an error, because x is not defined --

-- edited my_prog.py to add the x global now...
>> reload(my_prog)
>> print my_prog.x
-- prints x

However, if I instead to do a from my_prog import * in the beginning reload doesn't work, and doing the import again also has no effect.

like image 794
hugomg Avatar asked Apr 26 '11 16:04

hugomg


People also ask

How do I reload a .py file?

import importlib import inputs #import the module here, so that it can be reloaded. importlib. reload(inputs) from inputs import A # or whatever name you want. import inputs #import the module here, so that it can be reloaded.

What is the use reload () in Python?

The reload() is used to reload a previously imported module or loaded module. This comes handy in a situation where you repeatedly run a test script during an interactive session, it always uses the first version of the modules we are developing, even we have made changes to the code.

How do I start the Python interpreter in interactive mode?

On Windows, bring up the command prompt and type "py", or start an interactive Python session by selecting "Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI which includes both an interactive mode and options to edit and run files.


1 Answers

This has to do with the way Python caches modules. You need a module object to pass to reload and you need to repeat the import command. Maybe there's a better way, but here's what I generally use: In Python 3:

>> from importlib import reload
>> import my_prog
>> from my_prog import *
*** Run some code and debug ***
>> reload(my_prog); from my_prog import *
*** Run some code and debug ***
>> reload(my_prog); from my_prog import *

In Python 2, reload is builtin, so you can just remove the first line.

like image 164
Carl F. Avatar answered Oct 04 '22 00:10

Carl F.