在Python调用线程中捕获线程的异常总的来说,我对Python和多线程编程非常陌生。基本上,我有一个脚本可以将文件复制到另一个位置。我希望把这个放在另一个线程中,这样我就可以输出....指示脚本仍在运行。我遇到的问题是,如果无法复制文件,它将引发异常。如果在主线程中运行,这是可以的;但是,下面的代码不起作用:try:
threadClass = TheThread(param1, param2, etc.)
threadClass.start() ##### **Exception takes place here**except:
print "Caught an exception"在线程类本身中,我试图重新抛出异常,但它不起作用。我见过这里的人问过类似的问题,但他们似乎都在做一些比我想做的更具体的事情(而且我也不太明白所提供的解决方案)。我见过人们提到sys.exc_info()然而,我不知道在哪里或如何使用它。所有的帮助都是非常感谢的!编辑:线程类的代码如下:class TheThread(threading.Thread):
def __init__(self, sourceFolder, destFolder):
threading.Thread.__init__(self)
self.sourceFolder = sourceFolder
self.destFolder = destFolder def run(self):
try:
shul.copytree(self.sourceFolder, self.destFolder)
except:
raise
3 回答
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
thread_obj.start()
import sysimport threadingimport Queueclass ExcThread(threading.Thread): def __init__(self, bucket): threading.Thread.__init__(self) self.bucket = bucket def run(self): try: raise Exception('An error occured here.') except Exception: self.bucket.put(sys.exc_info())def main(): bucket = Queue.Queue() thread_obj = ExcThread(bucket) thread_obj.start() while True: try: exc = bucket.get(block=False) except Queue.Empty: pass else: exc_type, exc_obj, exc_trace = exc # deal with the exception print exc_type, exc_obj print exc_trace thread_obj.join(0.1) if thread_obj.isAlive(): continue else: breakif __name__ == '__main__': main()
慕后森
TA贡献1802条经验 获得超5个赞
concurrent.futures
import concurrent.futuresimport shutildef copytree_with_dots(src_path, dst_path): with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: # Execute the copy on a separate thread, # creating a future object to track progress. future = executor.submit(shutil.copytree, src_path, dst_path) while future.running(): # Print pretty dots here. pass # Return the value returned by shutil.copytree(), None. # Raise any exceptions raised during the copy process. return future.result()
concurrent.futures
futures
添加回答
举报
0/150
提交
取消