2015-11-23 194 views
0

我正在使用execnet在python腳本中調用jython模塊。Python Execnet和異常處理

docs

注意,從遠程執行的代碼的異常將被重新拋出作爲包含遠程回溯的文本表示channel.RemoteError異常。

假設我的遠程模塊可能導致兩個不同的異常,我希望能夠以不同的方式處理每個異常。我將如何處理這個問題,因爲這兩個例外都會拋出只包含一個追溯字符串的RemoteError異常?

例如,這個特殊的調用代碼:

#... 
channel.send('bogus') 

結果如下RemoteError,其中只包含一個包含回溯的字符串的屬性formatted

RemoteError: Traceback (most recent call last): 
    File "<string>", line 1072, in executetask 
    File "<string>", line 1, in do_exec 
    File "<remote exec>", line 33, in <module> 
IOError: Open failed for table: bogus, error: No such file or directory (2) 

我不能做try ... except IOError:。我可以做一個try ... except RemoteError as ex:並解析ex.formatted,看它是否含有IOError,然後提高該相反,但這似乎是相當稀鬆:

from execnet.gateway_base import RemoteError 
try: 
    channel.send('bogus') 
except RemoteError as ex: 
    if 'IOError' in ex.formatted: 
     raise IOError(ex.formatted[ex.formatted.find('IOError'): -1]) 
    if 'ValueError' in ex.formatted: 
     raise ValueError(ex.formatted[ex.formatted.find('ValueError'): -1]) 
    # otherwise, reraise the uncaptured error: 
    raise ex 

回答

0

一個老問題 - 我想回答這個問題

import unittest 
from execnet.gateway_base import RemoteError 
import execnet 

class Test(unittest.TestCase): 

    def RemoteErrorHandler(self,error): 
     e,t = error.formatted.splitlines()[-1].split(':') 
     raise getattr(__builtins__,e)(t) 

    def raising_receive(self, ch): 
     try: 
      return ch.receive() 
     except RemoteError as ex: 
      self.RemoteErrorHandler(ex) 

    def setUp(self): 
     self.gateway = execnet.makegateway() 


    def test_NameError(self): 
     ch = self.gateway.remote_exec("print o") 
     with self.assertRaises(NameError): 
      self.raising_receive(ch) 


if __name__ == '__main__': 
    unittest.main()