[英]try: except: not working
So I'm running into a problem where the try: except: mechanism doesn't seem to be working correctly in python. 所以我遇到了一个问题:try:except:机制似乎在python中没有正常工作。
Here are the contents of my two files. 这是我的两个文件的内容。
import pytest2
class MyError( Exception ):
def __init__( self, value ):
self.value = value
def __str__( self ):
return repr( self.value )
def func1():
raise MyError( 'This is an error' )
def func3():
pytest2.func2()
if __name__ == '__main__':
try:
func3()
except MyError, e:
print 'I should catch here.'
except:
print 'Why caught here?'
from pytest1 import func1
def func2():
func1()
Executing the first file yields the following output: 执行第一个文件会产生以下输出:
$ python pytest1.py
Why caught here?
Basically, the exception isn't being caught. 基本上,例外没有被抓住。 If I print out the exception type, it prints as
<pytest1.MyError>
instead of just <MyError>
. 如果我打印出异常类型,它将打印为
<pytest1.MyError>
而不是<MyError>
。 I imagine that this is some weird cyclical reference thing, but it still seems like it should work. 我想这是一些奇怪的周期性参考事物,但它似乎仍然应该工作。
The main python program is always imported as the module __main__
. 主python程序总是作为模块
__main__
导入。
When you import pytest2
, it doesn't reuse the existing module because the originally imported module has the name __main__
not pytest2
. 导入
pytest2
,它不会重用现有模块,因为最初导入的模块名称为__main__
而不是pytest2
。 The result is that pytest1
is run multiple times generating multiple exception classes. 结果是
pytest1
多次运行,生成多个异常类。 __main__.MyError
and pytest1.MyError
You end up throwing one and trying to catch the other. __main__.MyError
和pytest1.MyError
你最终抛出一个并试图抓住另一个。
So, don't try to import your main module from other modules. 因此,不要尝试从其他模块导入主模块。
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 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 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. 运行
python somefile.py
创建一个名为__main__
, 而不是 somefile
,并运行该模块中somefile.py
中的代码。 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. 这就是为什么
if __name__ == '__main__':
用于检查此文件是作为脚本运行还是从其他文件导入。
... at a guess, you have a namespace problem which is producing a different exception. ...猜测,你有一个命名空间问题,产生了一个不同的异常。
Try replacing 尝试更换
except:
print 'Why caught here?'
with 同
except Exception, e:
print e
This may tell you more about what went wrong. 这可能会告诉您更多关于出了什么问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.