You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python print赋值返回None:如何捕获Auto Scaling的DesiredCapacity值

问题

执行以下Python代码时,尝试将print输出的AWS Auto Scaling组DesiredCapacity值赋值给变量,但变量返回None。实际循环中print已输出整数值4,希望捕获该值用于后续代码。

代码:

import boto3
client = boto3.client('autoscaling')
clearesponse = client.describe_auto_scaling_groups(
    AutoScalingGroupNames=[
        'XXXX',
    ])


for reservation in clearesponse ['AutoScalingGroups']:
        test=print(reservation['DesiredCapacity'])


nb_desired_cap = test
print (nb_desired_cap)
print (test)

执行命令:python describe_instances.py

执行结果:

4
None
None

原因分析

print()函数的作用是将内容输出到控制台,它没有返回值(或者说返回值固定为None)。你把print()的返回值赋值给变量test,自然得到的是None。控制台输出的4是print()函数本身打印的内容,和变量test的取值无关。

解决方法

直接将reservation['DesiredCapacity']赋值给变量,不要通过print()中转:

修正后的代码

import boto3
client = boto3.client('autoscaling')
clearesponse = client.describe_auto_scaling_groups(
    AutoScalingGroupNames=[
        'XXXX',
    ])

# 直接赋值给变量,需要时再打印
for reservation in clearesponse['AutoScalingGroups']:
    test = reservation['DesiredCapacity']
    print(test)  # 按需打印

nb_desired_cap = test
print(nb_desired_cap)
print(test)

补充说明

如果AutoScalingGroups列表中只有一个目标组,也可以直接通过索引获取值,无需循环:

# 直接取第一个Auto Scaling组的DesiredCapacity
test = clearesponse['AutoScalingGroups'][0]['DesiredCapacity']
print(test)
nb_desired_cap = test
print(nb_desired_cap)

内容的提问来源于stack exchange,提问作者Cube_Cube_Cube_Cube

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 17:38:17