5

I am using a linux python shell and each time I make changes to the imported file I need restart the shell (I tried reimporting the file but the changes were not reflected)

I have a definition in a file called handlers.py

def testme():
    print "Hello I am here"

I import the file in the python shell

>> import handlers as a
>> a.testme()

>>  "Hello I am here"

I then change print statement to "Hello I am there", reimport handlers, it does not show the change?

Using Python 2.7 with Mint 17.1

peterretief
  • 2,049
  • 1
  • 15
  • 16
  • possible duplicate of [How to re import an updated package while in Python Interpreter?](http://stackoverflow.com/questions/684171/how-to-re-import-an-updated-package-while-in-python-interpreter) – fredtantini Sep 16 '14 at 10:43

3 Answers3

9

You need to explicitly reload the module, as in:

import lib # first import
# later ....
import imp
imp.reload(lib)  # lib being the module which was imported before

note that imp module is pending depreciation in favor of importlib and in python 3.4 one should use: importlib.reload.

behzad.nouri
  • 74,723
  • 18
  • 126
  • 124
  • In python 2 the ``reload`` function is a built-in function. No need to import imp, just ``reload(lib)``. – Nagasaki45 Sep 16 '14 at 10:43
  • 2
    @Nagasaki45 and perhaps there was some reason that it was removed from python 3. either case it would be much better to go with more cross-platform code. – behzad.nouri Sep 16 '14 at 10:45
1

You should use reload every time you make a change and then import again:

reload( handlers )
import handlers a a
Jose Varez
  • 2,019
  • 1
  • 12
  • 9
1

As an alternative answer inside reload you can use watchdog .

A simple program that uses watchdog to monitor directories specified as command-line arguments and logs events generated:

From the website

Supported Platforms

  • Linux 2.6 (inotify)

  • Mac OS X (FSEvents, kqueue)

  • FreeBSD/BSD (kqueue)

  • Windows (ReadDirectoryChangesW with I/O completion ports; ReadDirectoryChangesW worker threads)

  • OS-independent (polling the disk for directory snapshots and comparing them periodically; slow and not recommended)

Mazdak
  • 105,000
  • 18
  • 159
  • 188