Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python does not show code changes from imported file

Tags:

python

import

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

like image 469
peterretief Avatar asked Sep 16 '14 10:09

peterretief


3 Answers

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.

like image 64
behzad.nouri Avatar answered Nov 13 '22 02:11

behzad.nouri


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

reload( handlers )
import handlers a a
like image 43
Jose Varez Avatar answered Nov 13 '22 02:11

Jose Varez


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)

like image 1
Mazdak Avatar answered Nov 13 '22 03:11

Mazdak