Restart Python program if source has been modified

One of the nice features of developing a project with Django's development server, is the server's ability to restart/reload the project if its source has been modified.

I wanted to accomplish the same thing for an arbitrary Python program, and thus wrote a script, SourceChangeMonitor, to monitor a Python program for changes in the source code, and restart it when a change is detected.

Download:, a Python source code monitor

To make it work with your Python project, you have to edit some constants:

# How often should we check for changes (in seconds)
# Which files should be monitored for changes?
# Here, we deliberately exclude files beginning with a dot (.)
FILE_PATTERN = r"[!.]*.py"
# Which directory is the root of the source files?
ROOT_DIRECTORY = r"/home/jesper/projects/SourceChangeMonitor"
# Entry point program to run

POLL_INTERVAL defines how many seconds should pass between each check for changes. 1 second is fine for development scenarios.

FILE_PATTERN determines which files of the project should be monitored for changes. The pattern in the example chooses all files with the extension .py, that do _not_ start with a dot.

ROOT_DIRECTORY sets the top-level directory of your project.

PROGRAM is the entry point program to your project. (The file you would normally execute to run the project)

Normally, there is no need to edit the first two constants, but ROOT_DIRECTORY and PROGRAM should be set to match your project.

With the setup complete, you now run your project by running (or whatever you decide to call it :-) )

About the author

Jesper Borgstrup Jesper is a Masters student of computer science at the University of Copenhagen.

Leave a Reply

Your email address will not be published. Required fields are marked *

* Copy This Password *

* Type Or Paste Password Here *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>