通过python查找文件中的字符串总是失败



我创建了一个函数,用于获取要在日志文件中搜索的几个字符串。如果文件中存在所有字符串,该函数将返回True。else:函数将返回False。该函数还创建了所有缺失字符串的列表并打印该列表。

我使用readlines()函数来逐行搜索每个字符串。我正在搜索的文件是有效的,理论上所有的字符串都在其中,函数需要返回True。不知何故,它总是返回false并打印所有字符串[这是不应该发生的——如果所有字符串都存在,列表应该是空的]

我将附上我的代码下面,感谢帮助:


def pre_conditions():
with open(NR_log, 'r') as logfile:
name_key = 'Executing script: ' + recipe_name
app_key = 'Application was powered-up successfully, mode is: Review'
api_key = 'API recipe was chosen'
lot_key = 'Lot was created successfully'
recipe_key = 'Recipe execution started'
wafer_key = 'The Wafer was loaded successfully'
recipe_pause_key = 'Recipe run is paused'
program_key = 'Moving to Program mode'
recipe_creation_key = 'Recipe was saved successfully under the name: sanity_2022-06-22_Ver_5.1'
lst1 = lst
for line in logfile.readlines():
if name_key not in logfile:
lst.append('nError: Script was not successfully executed.n')
if app_key not in logfile:
lst.append('nError: Application was failed to power up.n')
if api_key not in logfile:
lst.append("nError: Recipe type [API] was not successfully chosen.n")
if lot_key not in logfile:
lst.append("nError: A lot was not successfully created.n")
if recipe_key not in logfile:
lst.append("nError: A timeout, recipe was not executed.n")
if wafer_key not in logfile:
lst.append("nError: The wafer was not loaded.n")
if recipe_pause_key not in logfile:
lst.append("nError: The recipe was not paused.n")
if program_key not in logfile:
lst.append("nError: The script was not switch to program key.n")
if recipe_creation_key not in logfile:
lst.append("nError: The recipe was not saved.n")
if not lst:
return True, print("Pre conditions are OK.")
return False, pre_conditions_failed_list_print(lst1)

def pre_conditions_failed_list_print(lst1):
for x in list(OrderedDict.fromkeys(lst1)):
print(x)

pre_conditions()

像这样的东西应该做你的工作的肉,我认为,我把字符串等的返回留给你:)。

keys = [name_key, app_key, <fill in your keys>]
found_key = {key: False for key in keys}
for line in logfile.readlines():
for key in keys:
if key in line:
found_key[key] = True

您需要检查您读取的行,而不是logfile实例

with open(NR_log, 'r') as logfile:
lines = [line.strip() for line in logfile.readlines()]
if name_key not in lines:
lst.append('nError: Script was not successfully executed.n')
....

最新更新