So I\'m running into a problem where the try: except: mechanism doesn\'t seem to be working correctly in python.
Here are the contents of my two files.
This problem is caused by importing the script you are running as a module. This produces two separate copies of the module!
Another example:
module.py
import module
class Foo: pass
def test():
print Foo
print module.Foo
print Foo is module.Foo
if __name__ == '__main__': test()
main_script.py
import module
if __name__ == '__main__': module.test()
Result
>python main_script.py
module.Foo
module.Foo
True
>python module.py
__main__.Foo
module.Foo
False
Running python somefile.py
creates a module called __main__
, not somefile
, and runs the code in somefile.py
in that module. This is why if __name__ == '__main__':
is used to check if this file is being run as a script or imported from some other file.