如何使用python处理错误?

2024-05-16 22:20:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在比较下面程序中的两个文件。如果它是一样的,那么我是印刷成功,否则作为失败。我正在使用一个名为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

詹金斯控制台输出:

^{pr2}$

Tags: 文件工具程序read电子邮件asstatuserror
3条回答

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

我不认为捕捉异常有什么意义,如果我们的目标是看到什么地方出了问题,让詹金斯的工作失败。在

编辑:如果您真的想显式打印失败的成功:

^{pr2}$

实际上不需要编写自己的代码来执行此操作,因为您只需要重新实现现有的^{}Unix命令,如果您使用的是Windows,^{}命令。在

您可以在Jenkins工作区中执行以下操作之一:

# UNIX shell
cmp file1 file2 || send email

我不太熟悉Windows脚本,但类似这样的方法应该可以奏效:

^{pr2}$

如果你真的想让你自己的Python脚本来做这件事。。。。。在

Jenkins将从shell(或类似的命令解释器)中执行脚本。要传达比较结果,可以使用sys.exit()设置进程的“退出状态”。通常,如果某个命令的退出状态为0,则该命令成功;否则,该命令将失败;因此,如果文件相同,则可以使用0;如果文件不相同,则可以使用1(或存在错误)。在

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)

然后在你的詹金斯工作区:

python compare_files.py file1 file2 || send email

或者

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

您可以使用allizip_longest逐行比较,这样就不会同时在内存中有两个完整的文件,并在出现错误时返回任何{a1}:

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

任何数字条0或1都表示发生了错误。在

^{pr2}$

相关问题 更多 >