关于使用装饰器捕获错误

4m1*_*4j1 0 python decorator python-multithreading python-decorators

我试图用装饰器捕获线程错误:

class cc:
    def catch_exceptions(job_func):
        @functools.wraps(job_func)
        def wrapper(*args, **kwargs):
            try:
                job_func(*args, **kwargs)
            except:
                import traceback
                print(traceback.format_exc())
            return wrapper

    @catch_exceptions
    def job(self, name, command):
        #print("I'm running on thread %s" % threading.current_thread())
        os.system(command)

    def run_threaded(self, job_func, name, command):
        job_thread = threading.Thread(target=job_func, args=(name, command,) )
        job_thread.start()
Run Code Online (Sandbox Code Playgroud)

我遇到了这个问题:

File "/usr/local/lib/python2.7/dist-packages/schedule/__init__.py", line 320, in do
self.job_func = functools.partial(job_func, *args, **kwargs)
TypeError: the first argument must be callable
Run Code Online (Sandbox Code Playgroud)

我怎样才能使job_func可调用?

Mar*_*ers 5

你的装饰器中的缩进是错误的;取消缩进该return wrapper行。

按照目前的情况,您的装饰器返回None,因此cc.job设置为None

更正后的版本将是:

def catch_exceptions(job_func):
    @functools.wraps(job_func)
    def wrapper(*args, **kwargs):
        try:
            job_func(*args, **kwargs)
        except:
            import traceback
            print(traceback.format_exc())
    return wrapper
Run Code Online (Sandbox Code Playgroud)

您可能想避免except在那里使用完全裸露的;您现在也捕获键盘中断和系统退出异常。在一个无关紧要的线程中(如果未捕获异常,无论如何都不会传播到主线程),但通常except Exception:您至少想使用。

  • 你的空白 except 捕获了所有内容,` except Exception` 过滤掉了一些。 (2认同)