shell上的打印异常

qmelpv7a  于 2021-06-26  发布在  Hive
关注(0)|答案(2)|浏览(395)

在下面的代码中,每当捕获到异常时,我都希望退出程序并在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)

下面是调用自定义项的转换查询:
使用mytable中的“python stream.py”as(id,name)创建表newtable as select transform(id,name);
我很欣赏你的想法。

xam8gpfp

xam8gpfp1#

如果你期待一个特定的异常,那么你应该捕获它,而不是所有的东西,这就是你正在做的。但是在你的代码中没有任何东西可以生成一个“找不到文件”!
编辑:问题代码已更改!我们真的希望捕捉“一切”。我正在使用 Exception ,它几乎可以捕获所有的东西,看到了吗https://docs.python.org/2/library/exceptions.html
它使用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)
mbyulnm0

mbyulnm02#

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

except IOError as e:

并使用访问错误字符串 e.strerror 如果要捕获所有异常,可以使用 sys.exc_info()[0] 访问上一条错误消息
例如

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

将打印

<type 'exceptions.ZeroDivisionError'>

相关问题