简体   繁体   中英

how to handle errors using python?

I am comparing two files in my program below. If it is same then I am printing as success else as failure. I am using a integrating tool called jenkins to send an email when it is failure in comparing the files, to do this - I have to handle the error properly. Can someone tell me how to handle the error ?

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

jenkins console output :

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

It is not really necessary to write your own code to do this, because you will just be reimplementing the existing cmp(1) Unix command, or the fc command if you are using Windows.

You can do one of the following in your Jenkins workspace:

# UNIX shell
cmp file1 file2 || send email

I'm not au fait with Windows scripting, but something like this should work:

rem Windows batch file
FC /B file1 file2
IF %ERRORLEVEL% NEQ 0 SEND_EMAIL_COMMAND

If you really want your own Python script to do this.....

Jenkins will execute your script from within a shell (or similar command interpreter). To communicate the result of the comparison you can set the process' exit status using sys.exit() . The convention is that a command was successful if it's exit status is 0, otherwise it failed, so you could use 0 when the files are the same, and 1 when they are not (or there was an error).

import sys

def compare_files(file1, file2):
    try:
        with open(file1, 'rb') as f_file1, open(file2, 'rb') as f_file2:
            return f_file1.read() == f_file2.read()
    except Exception as exc:
        print 'compare_files(): failed to compare file {} to {}: {}'.format(file1, file2, exc)
    return False

if __name__ == '__main__':
    if len(sys.argv) >= 3:
       if not compare_files(sys.argv[1], sys.argv[2]):
           sys.exit(1)
    else:
        print >>sys.stderr, 'Usage: {} file1 file2'.format(sys.argv[0])
        sys.exit(2)

Then in your Jenkins workspace:

python compare_files.py file1 file2 || send email

or

call python compare_files.py file1 file2
IF %ERRORLEVEL% NEQ 0 SEND_EMAIL_COMMAND

You can compare line by line using all and izip_longest so you won't have two whole files in memory at once and return any errno when an error is raised:

from itertools import izip_longest

def compare_files(file1, file2):
    try:
        with open(file1, 'rb') as f_file1, open(file2, 'rb') as f_file2:
            return all(l1 == l2 for l1, l2 in izip_longest(f_file1, f_file2, fillvalue=""))
    except EnvironmentError  as e:
        print("File is NOT compared, error message {}".format(e))
        return e.errno

Any number bar 0 or 1 will mean an error was raised.

In [4]: compare_files("same1.txt","same2.txt")
Out[4]: True

In [5]: compare_files("foo","bar")
File is NOT compared,error message [Errno 13] Permission denied: 'foo'
Out[5]: 13
In [6]: compare_files("test1","test2")
File is NOT compared,error message [Errno 21] Is a directory: 'foo'
Out[6]: 21
In [7]: compare_files("does_not_exist.txt","foo")
File is NOT compared,error message [Errno 2] No such file or directory: 'does_not_exist.txt'
Out[7]: 2
In [8]: compare_files("log.txt","out.txt")
Out[8]: False

Use assert . It will exit throwing an exception, so you will get the traceback will be written to the output and the Jenkins task will fail.

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()

I don't see the point in catching exceptions if the goal is exactly to see what went wrong and make the Jenkins job fail.

EDIT: If you really want to print SUCCESS of FAILURE explicitly:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM