哪里出错了?执行(编译(脚本,“<string>”,'exec'))

Where error happened? exec(compile(script,"<string>",'exec'))

我有 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

您需要将 function.foo 设为静态方法。

class function:
    @staticmethod
    def foo(parameter):
        a = parameter
        print(a)  # or e.g. causing the error print(a+'sss')
  1. \nscript="a=1\nb=3\nfunction.foo(2)" 语句中丢失。
  2. By static method: 使用静态方法调用静态函数。 className.FunctionName().
  3. 通过class方法:创建class方法,例如foo1() 并通过 class 实例调用,例如类名().函数名()

test.py

import sys
import traceback
from test1 import function

script="a=1\nb=3\nfunction.foo(2)"  # of e.g. script="a=1\nb=3\function.foo(2, 3)" 
try:exec(compile(script,"<string>",'exec'))
except:print traceback.format_exc()

script="a=1\nb=3\nfunction().foo1(33)"  # of e.g. script="a=1\nb=3\function.foo(2, 3)" 
try:exec(compile(script,"<string>",'exec'))
except:print traceback.format_exc()

script="a=1\nb=3\nfunction().foo1(c)" 
try:exec(compile(script,"<string>",'exec'))
except NameError, e:
    print "NameError exception, ", traceback.format_exc()
except:
    print traceback.format_exc()

test1.py

class function:
    @staticmethod
    def foo( parameter):
        a = parameter
        print "in foo:", a  # or e.g. causing the error print(a+'sss')

    def foo1(self, parameter):
        a = parameter
        print "in foo1:", a   # or e.g. causing the error print(a+'sss')

输出:

$ python test.py 
in foo: 2
in foo1: 3
NameError exception,  Traceback (most recent call last):
  File "test.py", line 1527, in <module>
    try:exec(compile(script,"<string>",'exec'))
  File "<string>", line 3, in <module>
NameError: name 'c' is not defined
import sys, traceback
from Catch_errors.my_function import function

script = "a=1\nb=3\nfunction().foo(a)"

try:
    compiled_script = compile(script,"<string>",'exec')
    exec(compiled_script)
except:
    exc_type, exc_obj, exc_tb = sys.exc_info()
    tr = traceback.extract_tb(sys.exc_info()[-1])
    print(tr)
    if "my_function.py" in tr[-1][0]:
        print("EXCEPTION IN FUNCTION "+str(tr[-1][-2])+"(), line '"+tr[-1][-1]+"'.")
        print(exc_obj.args[0])
    else:
        print('EXCEPTION IN USER SCRIPT: {}'.format(exc_obj))