try: except: not working

后端 未结 3 2196
青春惊慌失措
青春惊慌失措 2021-02-20 13:48

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.

pyte

3条回答
  •  南方客
    南方客 (楼主)
    2021-02-20 14:23

    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.

提交回复
热议问题