如何在 asyncio create_task 中更新全局变量 [英] How to update global variable in asyncio create_task

查看:99
本文介绍了如何在 asyncio create_task 中更新全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个未在整个应用程序中设置的全局变量.我有两个文件,其中 file2 从 file1 导入.全局在 file1 中初始化.

I currently have a global variable that's not being set across the application. I have two files where file2 imports from file1. The global is intialized in file1.

这是初始化全局变量并随后在文件 1 中使用它的代码.

Here is the code that initializes the global variable and later uses it in file1.

import time
import asyncio

#Initialize global
CONNECTION_OPEN = False

async def calculate_idle(t):
    orig_time = t
    global CONNECTION_OPEN
    while True:
        await asyncio.sleep(5)
        print("GLOBAL CONNECTION", CONNECTION_OPEN)
        if CONNECTION_OPEN:
            print("This value is now true")
        else:
             print("Value is still false")

这是将全局设置为 true 的 websocket 代码.它位于 file2 中.

Here is the websocket code that is setting the global to true. This is located in file2.

import os
import asyncio
import websockets
import json
import threading
import time
from random import randrange
from enum import Enum
from lights import calculate_idle,CONNECTION_OPEN 

async def init_connection(message):
    #Get global variable to set
    global CONNECTION_OPEN
    global CLIENT_WS
    uri = WS_URI
    async with websockets.connect(uri) as websocket:
        print("Setting Connection open to true")
        CONNECTION_OPEN = True
        CLIENT_WS = websocket
        # send init message
        await websocket.send(message)
        print("Connection is open") 
        while CONNECTION_OPEN:
            await handleMessages(websocket, message)
        await websocket.send(json.dumps({'type': MessageType.Close.name, 'message': USERNAME}))
        await websocket.close()

这是在file2中调用这段代码的方式

Here is how this code is called in file2

async def main():
    message = json.dumps({'payload': 
                            'payload')
    loop = asyncio.get_event_loop()
    start_light = asyncio.create_task(calculate_idle(3))
    await asyncio.gather(init_connection(message), start_light)

asyncio.run(main())

事件的顺序是:

  • CONNECTION_OPEN 设置为 false
  • 设置连接打开为真"是印刷
  • 打印连接已打开"
  • 值仍然为假"是重复打印

我希望更新全局变量值,以便打印此值现在为真".

I'd like the global variable value to be updated so that "This value is now true" is printed.

推荐答案

此行与您认为的不同:

from lights import calculate_idle,CONNECTION_OPEN 

它不会使 CONNECTION_OPEN 成为 lights.CONNECTION_OPEN 的别名;它将创建一个 new 全局变量(局部于 file2),用 lights.CONNECTION_OPENcurrent 值初始化.

It won't make CONNECTION_OPEN an alias for lights.CONNECTION_OPEN; it will create a new global variable (local to file2) initialized with the current value of lights.CONNECTION_OPEN.

在模块之间共享全局变量的正确方法是只import灯(无论如何这可能是个好主意)并使用lights.CONNECTION_OPEN.

The correct way to share a global among modules is to just import lights (which might be a good idea anyway) and use lights.CONNECTION_OPEN.

更好的选择是根本不使用全局变量,而是创建一个包含共享状态的可变对象,并将其传递给需要共享它的代码.您还可以按照@gold_cy 的建议,将状态添加到其他事物所需的现有对象中,例如 asyncio.Event.

A better option is to not use a global variable at all, but to create a mutable object that contains the shared state, and pass it to the code that needs to share it. You can also add the state to an existing object needed for other things, such as an asyncio.Event, as suggested by @gold_cy.

这篇关于如何在 asyncio create_task 中更新全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆