You ought to stick this whole block in a function called `main` and change your `if __name__ ==  '__main__':` block to just call that.