如何使用python处理错误?

sam*_*am 5 python python-2.7 jenkins

我在下面的程序中比较两个文件.如果它是相同的那么我打印成功就像失败一样.我正在使用一个名为jenkins的集成工具,在比较文件失败时发送电子邮件,这样做 - 我必须正确处理错误.有人能告诉我如何处理错误吗?

Error_Status=0
def compare_files(file1, file2):
   try:
       with open(file1, 'rb') as f_file1, open(file2, 'rb') as f_file2:
           if f_file1.read() == f_file2.read():
               print 'SUCCESS \n'
               #print 'SUCESS:\n  {}\n  {}'.format(file1, file2)
           else:
               print 'FAILURE \n'
               Error_Status=1
    except IOError:
        print "File is NOT compared"
        Error_Status = 1
Run Code Online (Sandbox Code Playgroud)

詹金斯控制台输出:

E:\Projekte\Audi\Cloud_SOP17_TTS>rem !BUILD step: Execute test: tts.py 

E:\Projekte\Audi\Cloud_SOP17_TTS>call python tts.py file1 file2   || echo failed 
INPUT ENG: I am tired
Latency: 114msec



[ERROR] Can't Create Reference PCM or Response JSON files!
INPUT GED: facebook nachricht schönes wetter heute
Latency: 67msec
INPUT GED: erinnere mich an den termin heute abend
Latency: 113msec

E:\Projekte\Audi\Cloud_SOP17_TTS>echo Started at: 15:51:25.37 
Started at: 15:51:25.37

E:\Projekte\Audi\Cloud_SOP17_TTS>exit 0 
Archiving artifacts
Recording plot data
Saving plot series data from: E:\Projekte\Audi\Cloud_SOP17_TTS\Backups\tts_2016_02_04.py
Not creating point with null values: y=null label= url=
No emails were triggered.
Finished: SUCCESS
Run Code Online (Sandbox Code Playgroud)

Elm*_*lmo -1

使用assert。它将退出并抛出异常,因此您将得到回溯将被写入输出,并且 Jenkins 任务将失败。

def compare_files(file1, file2):
    with open(file1, 'rb') as f_file1, open(file2, 'rb') as f_file2:
        assert f_file1.read() == f_file2.read()
Run Code Online (Sandbox Code Playgroud)

如果目标正是为了查看出了什么问题并导致 Jenkins 工作失败,我不认为捕获异常有什么意义。

编辑:如果您确实想明确打印成功或失败:

def compare_files(file1, file2):
    try:
        with open(file1, 'rb') as f_file1, open(file2, 'rb') as f_file2:
            assert f_file1.read() == f_file2.read()
    except:
        '''
        I know, I know. Normally we should catch specific exceptions.
        But OP wants to print SUCCESS or FAILURE and fail the Jenkins job
        in case of error.
        '''
        print 'FAILURE'
        raise
    else:
        print 'SUCCESS'
Run Code Online (Sandbox Code Playgroud)