Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 即使条件满足if语句,我的else语句也被执行了_Python_Boto3 - Fatal编程技术网

Python 即使条件满足if语句,我的else语句也被执行了

Python 即使条件满足if语句,我的else语句也被执行了,python,boto3,Python,Boto3,我在基于标记值关闭ec2实例方面取得了一些进展。但是,当我使用下面的脚本时,即使将标签“skip_shutdown”设置为“yes”,实例也关闭了电源。据推测,我希望这个实例不会被关闭,脚本只会在当天将标记值重置为“否”,以便在第二天关闭它 import boto3 import time from datetime import datetime #from pytz import timezone // not available in lambda #import pytz import

我在基于标记值关闭ec2实例方面取得了一些进展。但是,当我使用下面的脚本时,即使将标签“skip_shutdown”设置为“yes”,实例也关闭了电源。据推测,我希望这个实例不会被关闭,脚本只会在当天将标记值重置为“否”,以便在第二天关闭它

import boto3
import time
from datetime import datetime
#from pytz import timezone  // not available in lambda
#import pytz
import dateutil.tz
import os
import ast



ec2 = boto3.resource('ec2')

def lambda_handler(event, context):
    pacific = dateutil.tz.gettz('America/Los_Angeles')
    time_format='%H:%M'
    date = datetime.now(tz=pacific)
    print (f'Current PST time is: {date.strftime(time_format)}')
    current_time = date.strftime(time_format)
    #current_time = date.astimezone(timezone('US/Pacific')).strftime(date_format)

    #print (f'Current PST time is: {current_time}')

    # Get current time in format H:M
    # current_time = time.strftime("%H:%M")
    current_dayoftheweek = date.strftime("%A")
    #print(f'The current time: {current_time}')
    print(f'The current day of the week is: {current_dayoftheweek}')

    # Added holidays logic
    day_format='%m:%d'
    current_date = date.strftime(day_format)
    # holidays = ["05:13", "06:01"]
    # import holidays varialbe from environment variables
    holidays = os.environ['holidays']
    print(f'The current date is: {current_date}')
    print(f'The defined holidays is: {holidays}')

    

    # Python code to convert string to list
  
    def Convert(string):
        li = list(string.split(","))
        return li
      
    # Driver code    
    #str1 = "Geeks for Geeks"
    #print(Convert(str1))
    holidays = Convert(holidays)
    typeofholiday = type(holidays)
    print(f'The data type of the variable holidays is {typeofholiday}')
    

    # Find all the instances that are tagged with Scheduled:True
    filters = [{
        'Name': 'tag:Lambda_Managed',
        'Values': ['Yes']
    }
    ]

    # Search all the instances which contains scheduled filter
    instances = ec2.instances.filter(Filters=filters)

    # Define different schedule groups and start/stop time.
    
    # Application server schedule group
    # app_off = {'Monday': '22:15', 'Tuesday': '17:05', 'Wednesday': '15:37', 'Thursday': '22:00', 'Friday': '20:00'}
    # app_on = {'Monday': '5:00', 'Tuesday': '5:00', 'Wednesday': '16:01', 'Thursday': '5:00', 'Friday': '7:00', 'Saturday': '5:00'}
    app_off = os.environ['app_off']
    app_on = os.environ['app_on']
    # The environmental variables were imported as string type, need to be converted to dictionary data type to be used.
    #print(app_off)
    #variable_type = type(app_off)
    #print(variable_type)
    app_off = ast.literal_eval(app_off)
    app_on = ast.literal_eval(app_on)
    
    #new_variable_type = type(app_off)
    #print(new_variable_type)
    #a = app_off.get(current_dayoftheweek)
    #print(a)
    
    # Web server schedule group
    # web_off = {'Monday': '20:00', 'Tuesday': '22:00', 'Wednesday': '20:00', 'Thursday': '22:00', 'Friday': '20:00'}
    # web_on = {'Monday': '5:00', 'Tuesday': '5:00', 'Wednesday': '7:00', 'Thursday': '5:00', 'Friday': '7:00', 'Saturday': '5:00'}
    web_off = os.environ['web_off']
    web_on = os.environ['web_on']
    web_off = ast.literal_eval(web_off)
    web_on = ast.literal_eval(web_on)
    
    # SQL server schedule group
    # sql_off = {'Monday': '20:00', 'Tuesday': '22:00', 'Wednesday': '20:00', 'Thursday': '22:00', 'Friday': '20:00'}
    # sql_on = {'Monday': '5:00', 'Tuesday': '5:00', 'Wednesday': '7:00', 'Thursday': '5:00', 'Friday': '7:00', 'Saturday': '5:00'}
    sql_off = os.environ['sql_off']
    sql_on = os.environ['sql_on']
    sql_off = ast.literal_eval(sql_off)
    sql_on = ast.literal_eval(sql_on)

    
    # Stores list of instanceIDs
    stopInstances = []
    startInstances = []

    # Locate all instances that are tagged to start or stop.
    # ======crontab format===========
    # App Schedule Group:

    # minute  hour  (day of month)  month (day of week)

    # Power Off Triggers:
    # 0 20 * * 1,3,5
    # 0 22 * * 2,4
    # 
    # Power On Triggers:
    # 0 5 * * 1,2,4,6
    # 0 7 * * 3,5

    # python program to check if all values in the list equals to a value using traversal
    # This is used for checking if current_date is a holiday or not.
  
    def check(list1, val):
          
        # traverse in the list
        for x in list1:
      
            # compare with all the values
            # with val
            if val == x:
                return True 
        return False
    
    for instance in instances:

        # - before loop `for tag`-       

        Schedule_Name = None
        skip_shutdown = None

        # - loop `for tag ` -
        for tag in instance.tags:
            if tag['Key'] == 'Schedule_Name':
                Schedule_Name = tag['Value']
            elif tag['Key'] == 'skip_shutdown':
                skip_shutdown = tag['Value']


        # - after loop `for tag`-     Check which instance need to be off  
    
        if Schedule_Name == 'App' and current_time == app_off.get(current_dayoftheweek):
            if skip_shutdown == 'yes':
                # reset the tag value to "no" for this tag
                # tag['Value'] == 'no'
                instance.create_tags(Tags=[{"Key": 'skip_shutdown',"Value": 'no'}])
            else:
                # add this instance to stopInstances variable to stop it.
                stopInstances.append(instance.id)
        pass

        if Schedule_Name == 'Web' and current_time == web_off.get(current_dayoftheweek):
            if skip_shutdown == 'yes':
                # reset the tag value to "no" for this tag
                # tag['Value'] == 'no'
                instance.create_tags(Tags=[{"Key": 'skip_shutdown',"Value": 'no'}])
            else:
                # add this instance to stopInstances variable to stop it.
                stopInstances.append(instance.id)
        pass

        if Schedule_Name == 'Sql' and current_time == sql_off.get(current_dayoftheweek):
            if skip_shutdown == 'yes':
                # reset the tag value to "no" for this tag
                # tag['Value'] == 'no'
                instance.create_tags(Tags=[{"Key": 'skip_shutdown',"Value": 'no'}])
            else:
                # add this instance to stopInstances variable to stop it.
                stopInstances.append(instance.id)
        pass  

        
        # - after loop `for tag`-     Check which instance need to be on  
    
        if Schedule_Name == 'App' and current_time == app_on.get(current_dayoftheweek) and check(holidays,current_date) == False:
            # add this instance to startInstances variable to start it.
            startInstances.append(instance.id) 
        pass

        if Schedule_Name == 'Web' and current_time == web_on.get(current_dayoftheweek) and check(holidays,current_date) == False:
            # add this instance to startInstances variable to start it.
            startInstances.append(instance.id) 
        pass

        if Schedule_Name == 'Sql' and current_time == sql_on.get(current_dayoftheweek) and check(holidays,current_date) == False:
            # add this instance to startInstances variable to start it.
            startInstances.append(instance.id)  
        pass

    #print('current_time')
    #print(f'The current time: {current_time}')
    #print(f'The current day of the week is: {current_dayoftheweek}')




    # shut down all instances tagged to stop.
    if len(stopInstances) > 0:
        # perform the shutdown
        stop = ec2.instances.filter(InstanceIds=stopInstances).stop()
        print(f"Stopping instance: {stopInstances} - {current_time}")
    else:
        print("No instances to shutdown.")

    # start all instances tagged to start.
    if len(startInstances) > 0:
        # perform the start
        start = ec2.instances.filter(InstanceIds=startInstances).start()
        print(f"Starting instance: {startInstances} - {current_time}")
    else:
        print("No instances to start.")


首先,您可以使用
print()
查看变量中包含的内容以及真正执行的代码部分。这里没有足够的详细信息可供我们提供帮助。
实例的内容是什么?什么是
stopInstances
,以及以后在代码中是如何处理的?标记['Key']
标记['Value']
的计算结果是什么?是否可以在此处使用调试器(或仅打印出值,如@furas建议)?此外,除了根据文档创建标记外,该实例还做了什么:
instance.create_标记(标记=[{“Key:'skip_shutdown',“Value:'no'}])
?此外,您是否知道
for tag
循环基本上跳过了所有标记,但最后一个标记除外?@John Gordon Wow我甚至没有注意到(不是OP)。这似乎是一个很可能的原因。