带有Python的配置单元UDF-shell上的打印异常
在下面的代码中,每当捕获到异常时,我都希望退出程序并在shell上打印异常带有Python的配置单元UDF-shell上的打印异常,python,exception,hive,udf,Python,Exception,Hive,Udf,在下面的代码中,每当捕获到异常时,我都希望退出程序并在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')
#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的转换查询:
使用创建表newtable作为选择转换(id、名称)
mytable中的“python stream.py”作为(id,name)
想法受到赞赏。如果你期待一个特定的例外,那么你应该抓住它,而不是你正在做的一切。但是在你的代码中没有任何东西可以生成一个“未找到文件” 编辑:问题代码已更改!我们真的希望捕获“一切”。我使用的是
异常
,它“几乎”捕获了所有内容,请参见
这使用Python 2语法:
import sys
for line in sys.stdin.readlines():
try:
inpFile = "temp.py"
execfile(inpFile)
line1 = line.strip('\n').split('\t')
print "\t".join(line1)
except Exception as err:
print >> sys.stderr, err # print to stderr (python 2 syntax)
sys.exit(1)
如果要捕获特定类型的异常(例如IOError),可以使用
except IOError as e:
并使用e.strerror
如果要捕获所有异常,可以使用sys.exc\u info()[0]
访问最后一条错误消息
比如说
try:
1/0
except:
print sys.exc_info()[0]
将打印
<type 'exceptions.ZeroDivisionError'>
是,但“打印”会打印表中的链接。选中问题更正中的编辑-如果要在stderr上输出错误消息,可以使用print(“消息%s”,sys.exc_info()[0],file=sys.stderr)抛出语法错误,file=sys.stderr是否将错误写入文件?否,它将错误写入错误io流。有关标准io流的说明,请参见print(…,file=sys.stderr)
是Python3语法(或print\u函数,来自future)。很明显,OP使用的是Python2。是的,但是“print”会打印表中的链接。选中问题中的edit No Luck,上面的脚本正在引发运行时异常“org.apache.hadoop.hive.ql.metadata.HiveException:[Error 20003]:尝试关闭运行自定义脚本的运算符时出错”。听起来您不允许在hadoop中使用sys.exit(1)
。也许这个异常是由于您退出时出错引起的,但我猜是这样的。我没有任何hadoop的经验。也许您应该写入shell程序正在使用的控制台或tty(依赖于操作系统)。我想这就是你所说的“除外壳外的打印”的意思。