我正在尝试在使用BOTO3的同时处理NOLE或空列表异常。我想知道Pythonic码写这个有没有好方法。

try:        
    my_region = os.environ['AWS_REGION']
    if my_region == 'us-east-1':
        try:
            s3 = boto3.client('s3')
            buckets_list = s3.list_buckets()
        except Exception as err:
            logging.error('Exception was thrown in connection %s' % err)
            print("Error in connecting and listing bucket{}".format(err))
        if buckets_list['Buckets']:
            # Search for all buckets.
            for bucket in buckets_list['Buckets']:
            # my code follow to get other things...
            
        else:
            print("Buckets are empty in this region")
    else:
        print("Region not available")
        raise Exception("Exception was thrown in Region")    

except Exception as err:
    logging.error('Exception was thrown %s' % err)
    print("Error is {}".format(err))
    raise err

这是正确的方式还是任何建议都会有所帮助。

分析解答

您可以使用除套件之外的尝试else块。如果如果尝试子句不会提出异常必须执行的代码是有用的。

try:
    s3 = boto3.client('s3')
    buckets_list = s3.list_buckets()
except Exception as err:
    logging.error('Exception was thrown in connection %s' % err)
    print("Error is {}".format(err))
else:
    # This means the try block is succeeded, hence `buckets_list` variable is set.
    for bucket in buckets_list['Buckets']:
        # Do something with the bucket

我从代码中看到的一个问题是,如果list_buckets调用失败,有机会在if buckets_list['Buckets'] is not None:行上获取NameError。因为如果buckets_list调用失败,buckets_list未定义。要了解这一点尝试运行以下代码段:)

try:
    a = (1/0)
except Exception as e:
    print(e)

print(a)