if __name__ == '__main__' not working ipython

江枫思渺然 提交于 2019-12-23 09:27:32

问题


I'm having trouble getting the if __name == '__main__' trick to work in an IPython, Spyder environment. I've tried every approach given in this thread: if __name__ == '__main__' in IPython

Here are my super simplified modules

Module1.py

Class UnitTest():
    print 'Mod1 UnitTest!'

if __name__ == '__main__':
    UnitTest()

Module2.py

import Module1

Class UnitTest():
    print 'Mod2 UnitTest!'

if __name__ == '__main__':
    UnitTest()

So I run Module2.py and I always am seeing both Mod2 UnitTest and Mod1 UnitTest printed. These are executing in an IPython kernel. I want only the Mod2 UnitTest message to display.

Any idea what's up?


回答1:


Well I deleted this question earlier out of embarrassment but might as well share in case any other newb sees this.

I forgot to put the UnitTest line inside of the __init__ method. So the unit test was being run every single time when the class was defined and not when the object was instantiated. The code should be:

Module1.py

Class UnitTest():
    def __init__(self):
        print 'Mod1 UnitTest!'

if __name__ == '__main__':
    UnitTest()

Module2.py

import Module1

Class UnitTest():
    def __init__(self):
        print 'Mod1 UnitTest!'

if __name__ == '__main__':
    print 'Mod2 UnitTest!'


来源:https://stackoverflow.com/questions/31058930/if-name-main-not-working-ipython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!