在 boto3 中,在哪里放置 "if" 语句以仅输出具有空数组的值?

In boto3, where to put "if" statement to output only values with an empty array?

我正在使用 aws boto3,对编码还是很陌生,必须找到如何深入了解我的输出以仅 return 加载 balancers/target 没有目标连接的组。

  def gettargets(arn):
    tglist=elb.describe_target_health(TargetGroupArn=arn)
    targets=[]
    for targetid in tglist["TargetHealthDescriptions"]:
        targets.append(targetid['Target']['Id']) 
    print("Targets:",targets)

elbs = elb.describe_load_balancers(PageSize=100)
for loadbalancer in elbs["LoadBalancers"]:
    print("\n"*2)
    print("-"*8)
    print("ELB Name:",loadbalancer["LoadBalancerName"])
    print("Type:",loadbalancer["Type"])
    print("Scheme:",loadbalancer["Scheme"])
    print("TargetGroups:",str(gettargetgroups(loadbalancer["LoadBalancerArn"])))
    for tgs in gettargetgrouparns(loadbalancer["LoadBalancerArn"]):
     gettargets(tgs)

输出看起来像

    --------
ELB Name: example-elb
Type: application
Scheme: internet-facing
TargetGroups: ['example-tg']
Targets: ['i-09876543210']
    --------
ELB Name: example-alb-2
Type: application
Scheme: internal
TargetGroups: ['example-tg-2']
Targets: []

我需要帮助return处理 空目标的部分:[]

我应该在 getargets 函数中放置一个 if 语句还是在底部做一个 if 语句。 我可以阅读 python,但还不能概念化结构以及各个部分的工作原理。

你实际上 'return' 这里什么都没有,你只是在得到结果后立即将结果转储到屏幕上。

拆分逻辑和打印,就这样了。

def gettargets(arn):
    tglist=elb.describe_target_health(TargetGroupArn=arn)
    targets=[]
    for targetid in tglist["TargetHealthDescriptions"]:
        targets.append(targetid['Target']['Id']) 
    # now we return, not print!
    return targets



elbs = elb.describe_load_balancers(PageSize=100)
for loadbalancer in elbs["LoadBalancers"]:
    
    targets = []
    for tgs in gettargetgrouparns(loadbalancer["LoadBalancerArn"]):
        targets += gettargets(tgs)

    # print the whole stuff only if targets is empty
    if targets == []:
        print("\n"*2)
        print("-"*8)
        print("ELB Name:",loadbalancer["LoadBalancerName"])
        print("Type:",loadbalancer["Type"])
        print("Scheme:",loadbalancer["Scheme"])
        print("TargetGroups:", str(gettargetgroups( loadbalancer["LoadBalancerArn"])))
        print("Targets:",targets)

您可以只从 gettargets return targets,然后检查它是否为空:

  def gettargets(arn):
    tglist=elb.describe_target_health(TargetGroupArn=arn)
    targets=[]
    for targetid in tglist["TargetHealthDescriptions"]:
        targets.append(targetid['Target']['Id']) 
    return targets
    

elbs = elb.describe_load_balancers(PageSize=100)
for loadbalancer in elbs["LoadBalancers"]:
    targets = []
    
    for tgs in gettargetgrouparns(loadbalancer["LoadBalancerArn"]):
       targets += gettargets(tgs)

    if not targets:
        print("\n"*2)
        print("-"*8)
        print("ELB Name:",loadbalancer["LoadBalancerName"])
        print("Type:",loadbalancer["Type"])
        print("Scheme:",loadbalancer["Scheme"])
        print("TargetGroups:",str(gettargetgroups(loadbalancer["LoadBalancerArn"])))
        print("Targets:",  targets)