How to handle errors using python?

I am comparing two files in my program below. If it is the same, I print as success otherwise than failure. I use an integrated tool called jenkins to send emails when it is an error while comparing files, for this - I have to handle the error correctly. 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 
+5
source share
3 answers

It’s not really necessary to write your own code, because you simply override the existing cmp(1) Unix command, or fc if you are using Windows.

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

 # UNIX shell cmp file1 file2 || send email 

I'm not sure about Windows scripts, 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 the shell (or a similar command interpreter). To report the comparison result, you can set the exit status of the process using sys.exit() . The convention is that the command was successful if it completed status 0, otherwise it failed, so you could use 0 when the files match, 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 the 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 
+2
source

You can compare line by line using all and izip_longest so that there are no two whole files in memory at once and any errno returned when an error occurs:

 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 numeric string 0 or 1 will indicate that an error has been 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 
0
source

Use assert . It will exit the exception, so you will get a trace response 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 to understand what went wrong and make Jenkins work unsuccessful.

EDIT: If you really want to print FAILURE SUCCESS 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' 
-1
source

Source: https://habr.com/ru/post/1243121/


All Articles