赋值前引用的第 10 行封闭范围中定义的局部变量“count”

sai*_*mar 0 python python-3.x

我对以下 Python 3 代码有问题(从底部开始第 5 个位置的行count=count+1):

import base64
import json
from google.cloud import iot_v1
import os
from twilio.rest import Client

account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
client = Client(account_sid, auth_token)
count = 0


def device_config(config):
    client = iot_v1.DeviceManagerClient()
    name = client.device_path(<project_ID>,
                              <Region>,  <Registry>, <Device_ID>)
    binary_data = bytes(config, 'utf-8')
    client.modify_cloud_to_device_config(name, binary_data)


def hello_pubsub(event, context):
    if 'data' in event:
        data = event['data']
        data = base64.b64decode(data)
        data = data.decode('utf-8')
        data = json.loads(data)

        temperature = float(data['temperature'])

        if temperature > 25.0:
            device_config("ledon")
            if count < 1:
                client.calls.create( \
                    url=<URL>,
                    to=os.environ['TWILIO_TO'],
                    from_=os.environ['TWILIO_FROM'])
                count = count+1
        else:
            device_config("ledoff")
    else:
        print("Data is not present!")

Run Code Online (Sandbox Code Playgroud)

该函数将被连续调用(想象一下,无限循环将调用该函数)。我想在第一次温度超过 25 时将计数更新为 1,对于以后的调用,温度可能会达到多高,LED 应该亮起,但不应该进行调用

hir*_*ist 8

hello_pubsub(event, context)您分配给count行中count = count+1。这使得 python 在函数作用域中查找count(其中尚未定义,因此在右侧 [ count+1] 上查找失败)。

这可能是值得一读的:https://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html#variable-scope-and-lifetime

你需要告诉 python 你的意思是全局count

def hello_pubsub(event, context):
    global count
    ...
Run Code Online (Sandbox Code Playgroud)

可能更干净的是:

def hello_pubsub(count, event, context):
    ...
Run Code Online (Sandbox Code Playgroud)

然后使用以下方式调用它:

hello_pubsub(count, event, context)
Run Code Online (Sandbox Code Playgroud)