在多个特定的“字符串”python上引发异常

时间:2016-06-07 15:10:41

标签: python

我有一个包含以下内容的文件:

XYZname_1

XYZname_2

XYZname_3

在我的脚本中,我使用re.search检查名称是否不正确,如果他们是raise exception。如果两个名称都不正确,它只会在第一个引发异常,然后“崩溃”,换句话说,“用户”将不知道第二个或第三个名称是否不正确。

for my_file in args.cpath:
    contents = open(my_file).read()

    replaced_contents = my_func(contents,my_file)


def my_func(my_file_contents, filename):
    for x in range(0, 3):
        #Some code here which is not related to the problem

        #In this if-statement I check if it does not match with re.search
        #I assume a for-loop should be here? but not sure how to implement it. 
        if not re.search(r'(.*)XYZname_{0}\(\)\) = .*;(.*)'.format(x+1), my_file_contents):
            raise Exception("The name: XYZname_{0} was not found".format(x+1) + " in " + filename)

让我们说我们之前看到的名字就像这样写在一个文件中(他们错了)

XYZnameHE_1

XYZnameGJ_2

XYZnameAsd_3

然后我的脚本应该告诉我在给定文件中找不到XYZname_1,2和3。

当然也可能有其他名称,另一个功能需要处理。这些名称可以从XXXname_1,2 3等开始。如果其中一个丢失,我也会得到一个例外

现在我得到了这个输出:

Exception: The name: XYZname_1 was not found in C:\Path

但我想要这样的事情:

Exception: The name: XYZname_1 was not found in C:\Path
Exception: The name: XYZname_2 was not found in C:\Path
Exception: The name: XYZname_3 was not found in C:\Path
Exception: The name: XXXname_2 was not found in C:\Path

不知道解决这个问题的“最佳实践”是什么。一个选项是让脚本完成查看整个文件,然后“崩溃”/加注?或者只是在发现问题时直接“崩溃”/加注?因为开发人员多次运行脚本以查找所有错误/错误的名称会很烦人。

2 个答案:

答案 0 :(得分:1)

在列表中收集姓名/匹配项。然后,在循环之后,如有必要,引发异常。根据我的理解,您还需要findall()而不是search()

最后你会得到类似的东西:

matches = []
for x in range(0, 3):
     #Some code here which is not related to the problem

     # add the matches to the list
     matches.extend(re.findall(r'(?:.*)(XYZname_{0})\(\)\) = .*;(?:.*)'.format(x+1), my_file_contents))

if matches:
    for match in matches:
        print("The name: {0} was not found in {1}".format(match, filename))
    raise Exception(...)

我还将()替换为表达式中的(?:) - 替换了非捕获的捕获组。还在()周围添加XYZname_{0}以捕获名称。

答案 1 :(得分:0)

对迭代中的每个项目使用try / catch而不是单次传递:

for x in range():
    try:
        re.search ...
    except:
        raise exception ...

不是python专家,而是从纯粹的代码/逻辑角度来看,这应该可以解决问题。