if __name__ == '__main__' not working ipython

时间:2015-06-25 19:16:23

标签: python ipython spyder

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 个答案:

答案 0 :(得分:3)

我早些时候因为尴尬而删除了这个问题,但是如果其他任何新手看到这个问题,也可以分享。

我忘了将UnitTest行放在__init__方法中。因此,单元测试在定义类时每次运行,而不是在实例化对象时运行。代码应该是:

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!'