【发布时间】:2015-03-28 08:54:59
【问题描述】:
我有 2 个文件。其中一个脚本(从另一个文件调用函数)被编译并执行。我需要确定错误发生的位置:是在 user_script.py 中创建脚本(在脚本的哪一行)时出错,还是在 foo(parameter) 函数中出错。
我想捕获任何错误(SyntaxError、TypeError 等)并根据它是发生在脚本本身还是函数 foo(parameter) 中以不同方式处理它们
我展示了两个带有 NameError 的示例,但原则上我想对任何类型的错误做同样的事情。我应该参考哪些属性来区分它们?
示例 1
user_script.py
import sys
import traceback
from Catch_errors.my_function import function
script="a=1\nb=3\nfunction.foo(c)"
exec(compile(script,"<string>",'exec'))
my_function.py
class function:
def foo(parameter):
a = parameter
print(a) # or e.g. causing the error print(a+'sss')
输出:
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0\helpers\pydev\pydevd.py", line 2199, in <module>
globals = debugger.run(setup['file'], None, None)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0\helpers\pydev\pydevd.py", line 1638, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/Support/PycharmProjects/HelloWorldProject/Catch_errors/user_Script.py", line 7, in <module>
exec(compile(script,"<string>",'exec'))
File "<string>", line 3, in <module>
NameError: name 'c' is not defined
示例 2
user_script.py
import sys
import traceback
from Catch_errors.my_function import function
script="a=1\nb=3\nfunction.foo(2)"
exec(compile(script,"<string>",'exec'))
my_function.py
class function:
def foo(parameter):
a = parameter
print(b)
输出:
Traceback (most recent call last):
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0\helpers\pydev\pydevd.py", line 2199, in <module>
globals = debugger.run(setup['file'], None, None)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0\helpers\pydev\pydevd.py", line 1638, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 4.0\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/Support/PycharmProjects/HelloWorldProject/Catch_errors/user_Script.py", line 5, in <module>
script="a=1\nb=3\nfunction.foo("+b+")"
NameError: name 'b' is not defined
【问题讨论】:
-
另外,如果你准确地发布你的错误会有所帮助。
-
不,你的建议是错误的。它会导致 TypeError,而我的版本可以正常工作。但是,我不是在寻找创建正确脚本的方法,而是想捕捉用户可能犯的任何错误。我想捕获任何错误(SyntaxError、TypeError 等)并根据它是发生在脚本本身还是函数
foo(parameter)以不同方式处理它们 -
如果你的
script没有编译,你会得到一个SyntaxError。然而,向我们展示实际的追溯将使我们为您提供更好的帮助。 -
您必须自省回溯以确定异常发生在堆栈中的哪个位置。
-
我认为我的建议没有错。我只是没有注意到您的代码中的第二个错误(首先是在类名之后调用没有括号的类变量,第二个是缺少
\n。我还建议您包含“,但希望捕获任何可能的错误用户可以我想捕获任何错误(SyntaxError、TypeError 等)并根据它是发生在脚本本身还是您帖子中的函数 foo(parameter)" 而不是 cmets 中发生的不同来处理它们。
标签: python exception python-3.x exception-handling traceback