Skip to main content
 首页 » 编程设计

python之使用 Python 的 Hive UDF之在 shell 上打印异常

2024年10月24日8mayingbao

在下面的代码中,每当捕获到异常时,我想退出程序并在 shell 上打印异常

#stream.py 
import hashlib 
import sys 
import os 
import importlib 
 
 
for line in sys.stdin.readlines(): 
        try: 
            inpFile = "temp.py" 
            execfile(inpFile) 
            line1 = line.strip('\n').split('\t') 
            print "\t".join(line1) 
        except: 
            #exception expected "temp.py:File Not Found", how do I exit the code & print the exception on console ?  
            sys.exit(1) 

这是调用 UDF 的转换查询:

Create table newtable as Select TRANSFORM(id,name) USING 'python stream.py' as (id,name) from mytable;

赞赏想法。

请您参考如下方法:

如果你想捕获特定类型的异常(例如 IOError),你可以使用

  except IOError as e: 

并使用e.strerror访问错误字符串

如果你想捕获所有异常,你可以使用 sys.exc_info()[0] 访问最后的错误消息

例如

try: 
   1/0 
except: 
   print sys.exc_info()[0] 

会打印

<type 'exceptions.ZeroDivisionError'>