从1.0到1.6,磕磕绊绊了一个星期。从100行代码到30行代码,再到100行再到60行。bug不停,迭代不止。懵懂的小白终于实例化了第一个‘类’,尽管代码依旧臃肿丑陋,然而执行的结果足以令我欣喜不已。万事开头难,要走的路还很长,加油。
该实例实现从txt文件中读取数据生成字典,通过遍历字典中的数据完成逻辑处理,返回相应结果
import os
class StatusMonitor:
def __init__(self):
self.dict = {}
try:
base_dir = os.getcwd\..\untility #从工作路径向上寻找configfile所在的绝对路径
configfile_path = os.path.join(base_dir, 'configfile.txt') #获取configfile.txt
CONFIGFILE = open(configfile_path, 'r')
except:
print ("File not exist")
return False
for line in CONFIG:
(key,value) = line.strip().split(':')
self.dict[key] = value
def check_parameters(self):
#print (configfile)
#Check the config file for blank value
configfile = self.dict
for key in configfile:
if configfile[key] =='':
print ([key], "Error: Value is blank")
return False
else:
#print ([key,configfile[key]],'Pass')
pass
#Check the Test_hour/Cycle_time/change_prof_hour
test_hour = self.get_parameters('TEST_HOUR')
cycle_time = self.get_parameters('CYCLE_TIME')
change_prof_hour = self.get_parameters('CHANGE_PROFILE_HOUR')
test_type = self.get_parameters('TEST_TYPE')
execute_method = self.get_parameters('EXECUTE_METHOD')
if int(test_hour) < int(cycle_time):
print ("Error: test_hour < cycle time is incorrect")
return False
elif int(cycle_time) < int(change_prof_hour):
print ("Error: cycle_time < change_prof_hour is incorrect")
return False
elif (test_type != 'black')and(test_type)!= 'white':#or str(test_type) is not 'white':
print ("Error: test_type should be 'black' or 'white'.")
return False
#elif (execute_method) != '1' and (execute_method) !='2':
print ("Error: execute_method should be '1' or '2'")
return False
else:
print ("Check parameters completed.No error occurs")
return True
def get_parameters(self,item):
value = self.dict.get(item,None)
if value == None:
print (item,' key error')
return value
#Test
if __name__=='__main__':
i = StatusMonitor()
k = i.check_parameters()
print(k)