错误发生在哪里? EXEC(编译(脚本,&#34; <字符串>&#34;&#39; EXEC&#39;))</字符串>

时间:2015-01-29 07:52:53

标签: python exception python-3.x exception-handling traceback

我有2个文件。在其中一个中,编译并执行脚本(从另一个文件调用该函数)。我需要的是确定错误发生的位置:在user_script.py中创建脚本(脚本的哪一行)或foo(参数)函数中的错误是否是错误。

我想捕获任何错误(SyntaxError,TypeError等)并根据它是在脚本本身还是在函数foo(参数)中发生而对它们进行不同的处理

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

3 个答案:

答案 0 :(得分:2)

你需要使function.foo成为一个静态方法。

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

答案 1 :(得分:0)

    {li} \nscript="a=1\nb=3\nfunction.foo(2)"声明中失踪。
  1. 通过静态方法:使用静态方法调用静态函数。 className.FunctionName()
  2. 按类metohd:创建类方法,例如foo1()并按类实例调用,例如类名()。使用functionName()
  3. 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
    

答案 2 :(得分:0)

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))