ない、それを行うための最善の方法が、私はそれが一致(triggered_match)を見つけたら、それはテキストと一致したことがあったどのように多くのエントリを参照するサイクルを開始した後、ユーザー入力を受け付けることができたと。最後のマッチがTrueに設定された最後のマッチを見つけたら、triggered_matchをfalseに設定して、マッチの最下部にいることを知っていました。余分な変数 "first_match_only"は、最初にファイル全体で一致するものが見つかったときにのみ出力するようにします(ファイルの末尾に一致するものがもっとある場合)。ファイル内で一致するものが見つからなかった場合は、ファイルの末尾にエントリが追加されます。
import fileinput
import re
class Horcm():
driver = None
def __init__(self):
group_name = "test_123"
device_name = "test_1234"
array_serial = "8998"
array_ldev = "3794"
mirror_unit = "0"
IP_address = "xxx.xxx.xxx.xxx"
horcm102 = "horcm102"
found_in_file= self.horcm_match(group_name, device_name, array_serial, array_ldev, mirror_unit)
self.add_horcm_inst(found_in_file, group_name,device_name, array_serial, array_ldev, mirror_unit, IP_address, horcm102)
def horcm_match(self,group_name, device_name, array_serial, array_ldev, mirror_unit):
# initalize variables
previous_match = False
first_time_matching_only = False
found_in_file = False # used in add_horcm function
# search through file for matches
for line in fileinput.input(
r'path',
inplace=1):
triggered_match = False # reset trigger
line_data = line.strip() # removes the extra line that is automatically added
if group_name in line: # If the user input is found in the file
found_in_file = True # determine if it needs to be added to file or not
triggered_match = True # set trigger
previous_match = triggered_match # store trigger
if previous_match == True: # If the previous line had a match
if triggered_match == False: # If the next line doesn't have a match
if first_time_matching_only == False: # if this is the first time finding a match
previous_match = False
first_time_matching_only = True # Don't allow it to print other matches
print(group_name+" "+device_name+" "+array_serial+" "
+array_ldev+" "+mirror_unit) # print the match below the last match
print(line_data), # preserve old content
return found_in_file
def add_horcm_inst(self,found_in_file,group_name,device_name, array_serial, array_ldev, mirror_unit, IP_address, horcm102):
if not found_in_file : # If you find it in the file there is no reason to add it to the file
input_filename = 'path'
with open(input_filename, 'a') as file1: #open the file
file1.write(group_name+" "+IP_address+" "+horcm102) #add horcm_instance to bottom of file in right syntax
with fileinput.FileInput(input_filename, inplace=True) as file: #open file again to add to the bottom of the "HORCM_LDEV" list
for line in file: # read line by line
file_syntax = '#/************************* For HORCM_INST ************************************/' #find the bottom of the list
print(line.replace(file_syntax, group_name+" "+device_name+" "
+array_serial+" "+array_ldev+" "+mirror_unit+'\n'+'\n'+file_syntax), end='') # add to list followed by file_syntax again
def main():
Horcm()
if __name__ == '__main_' \
'_':
Horcm()