2013-03-22 145 views
0
def c1(): 
     logfile = open("D:\myfile.txt", 'r') 
     for num1, line in enumerate(logfile): 
       if "request=100" in line: 
        print num1 
        return True 
     return False 

    def c2(): 
     logfile = open("D:\myfile.txt", 'r') 
     for num2, line in enumerate(logfile): 
       if "response=200" in line: 
        print num2 
        return True 
     return False  

    if c1() == True and c2() == True: 
     print "Test Case Passed" 
    else: 
     print "Test Case Failed" 

在上面的代碼中,檢查行號以便request = 100和response = 200將落在同一行中不存在。我需要。查找在Python中搜索的字符串的行號

另外,我想打印結果爲「合格」只有滿足以下條件......

- both c1 and c2 are True 
- both "request=100" and "response=200" should fall in same line 
- if any other line also consist of "request=100" and "response=200" then that also should be counted 

結果是「失敗」,如果:

- if any one line which consists of "request=200" and "response=200" 
- if any one line which consists of "request=100" and "response=100" 
- or any case in which no line should have apart from "request=100" and "response=200" 

考慮「MYFILE 「有以下數據:

request=100 XXXXXXXXXXXXXXXXXXXXXXXXXXXX \n 
XXXXXXXXXXXXXXXX response=200 XXXXXXXXX \n 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \n 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \n 
XXXX request=100 XXXXX response=200 XXXXXXXXXXX \n 
XXXXXXX request=200 XXXXXX response=100 XXXXXXX \n 
XXXXXXXX request=100 XXXX response=100"   \n 

在上面的文件中,結果是失敗的,因爲請求和響應具有不同的值除了要求的值之外,只有第5行具有正確的值,因此結果失敗。

回答

0

如果我理解正確的話,你應該把兩個條件中的一個循環,並不斷循環,直到你遇到行的末尾,或者遇到其他符合條件:

def are_they_on_the_same_line(): 
    logfile = open("D:\myfile.txt", 'r') 
    intermediate_result = False 
    for num1, line in enumerate(logfile): 
      if "request=100" in line and "response=200": 
       if intermediate_result == True: 
        return False 
       intermediate_result = True 
    return intermediate_result 

還有其他的條件在這種情況下,除了你提到的失敗情況之外,這種情況會失敗。但是你提到的兩個不是相互排斥的。

編輯:不要等這是錯誤的,從這個例子來判斷。我無法理解你的條件。也許它可以幫助你得到一個想法,如果沒有,請用另一個例子來說明條件。