2016-06-07 107 views
0

我有一个包含一个文件:引发异常,蟒蛇

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 

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

+1

为什么不将缺少的名字存储在列表中,然后在列表中包含任何项目时结束? –

回答

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}以捕获该名称。

+0

嗯我试过了,但我的测试通过为绿色,即使名称是错误的。 – gants

+0

@gants可能是表达式的问题。我想你可能需要使用're.DOTALL'和're.MULTILINE'标志。你可以避免在模式开始和结束处使用'(?:。*)'部分。 – alecxe

+0

喜欢这个? (r.(?:。*)(XYZname_ {0})\(\)\)=。*;(?:。*)'.format(x + 1),my_file_contents) ,re.MULTILINE,re.DOTALL)'如果我添加它就会告诉我他们是“意外的地狱” – gants

0

使用尝试在每个项目/捕捉你的迭代,而不是单传:

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

不是蟒蛇专家但从纯代码/逻辑角度出发,应该做的伎俩。