如何在Python中执行一次脚本

时间:2018-07-02 15:30:01

标签: python monitoring

我有以下Python代码,并且只想执行一次ServiceRestart。

当前情况是我配置了四个错误,我的以下脚本将从JSON文件中获取错误并发送电子邮件警报,但由于我已在 else 下添加了服务重启,因此如果出现以下情况,它将重启服务4次:同时发现4个错误。

我只想运行serviceRestart一次。

        # Logic to read the result file and send email
    if self.flag:
        fn = open(result_file_name, 'r+')
        result_data = fn.read()
        self.logger.info('Calling send email method')
        self.logger.info(result_data)
        if(((day == 'Saturday') and (hr >= '06' and hr <'12')) or (day == 
        'Sunday')):
            print('Mail will not go')
        else:                
            self.email_util.send_email(result_data)
            serviceName = "raha-connector"
            win32serviceutil.RestartService(serviceName) //this i want to execute once
            result_data = 'Connector started successfully'
            self.email_util.send_email(result_data)
            self.logger.info('Match found, hence send email method called')
            self.logger.info('End of search_file method : file_name -%s, 
            criteria - %s, last scanned row - %s',
            file_name, criteria, last_scanned_row)

我尝试使用计数器,但无法正常工作。我什至尝试使用循环也无法正常工作。

请提供一些方法来执行serviceRestart,无论错误如何。

谢谢。

1 个答案:

答案 0 :(得分:1)

为此使用布尔值。

has_restarted = False
 # Logic to read the result file and send email
    if self.flag:
        fn = open(result_file_name, 'r+')
        result_data = fn.read()
        self.logger.info('Calling send email method')
        self.logger.info(result_data)
        if(((day == 'Saturday') and (hr >= '06' and hr <'12')) or (day == 
        'Sunday')):
            print('Mail will not go')
        else:                
            self.email_util.send_email(result_data)
            serviceName = "raha-connector"
            if not has_restarted:
                win32serviceutil.RestartService(serviceName) //this i want to execute once
                has_restarted = True
            result_data = 'Connector started successfully'
            self.email_util.send_email(result_data)
            self.logger.info('Match found, hence send email method called')
            self.logger.info('End of search_file method : file_name -%s, 
            criteria - %s, last scanned row - %s',
            file_name, criteria, last_scanned_row)

您有一个布尔值has_restarted,其开头是False。在我添加的if语句中使用重新启动功能后,has_restarted变为True,因此它将永远不会通过if语句,并且不会发出重新启动。