Python 如何在asyncio create_任务中更新全局变量
我目前有一个全局变量,它没有在整个应用程序中设置。我有两个文件,其中file2从file1导入。全局变量在文件1中初始化 下面是初始化全局变量的代码,稍后在file1中使用它Python 如何在asyncio create_任务中更新全局变量,python,python-3.x,python-asyncio,Python,Python 3.x,Python Asyncio,我目前有一个全局变量,它没有在整个应用程序中设置。我有两个文件,其中file2从file1导入。全局变量在文件1中初始化 下面是初始化全局变量的代码,稍后在file1中使用它 import time import asyncio #Initialize global CONNECTION_OPEN = False async def calculate_idle(t): orig_time = t global CONNECTION_OPEN while True:
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代码。这位于文件2中
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()
下面是如何在文件2中调用此代码
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())
事件顺序如下:
- 连接\u OPEN设置为false
- “将连接打开设置为true”是 印刷品
- 打印“连接已打开”
- “值仍然为假”是错误的 反复印刷
我希望更新全局变量值,以便打印“此值现在为真”。只需使用
asyncio.Event
对象作为全局变量即可
import time
import asyncio
async def calculate_idle(t, conn_open_event):
orig_time = t
while True:
await conn_open_event.wait()
print("Connection is now open from idle")
这一行并不像你想象的那样:
从灯光导入计算空闲,连接打开
它不会使连接打开
成为灯的别名。连接打开
;它将创建一个新的全局变量(本地到文件2
),该变量使用灯的当前值初始化。连接打开
在模块之间共享全局视图的正确方法是只导入灯光(无论如何这可能是个好主意)并使用灯光。连接\u打开
更好的选择是根本不使用全局变量,而是创建一个包含共享状态的可变对象,并将其传递给需要共享它的代码。您还可以将状态添加到其他事情所需的现有对象中,如@gold\u cy建议的
asyncio.Event
。您可能需要显示导入。或者构造一个产生相同行为的最小(自包含)示例。只添加导入。感谢不要使用全局变量,而是使用感谢!我可能会转向这个。
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
async def init_connection(message, conn_open_event):
#Get global variable to set
global CLIENT_WS
uri = WS_URI
async with websockets.connect(uri) as websocket:
print("Connection is open from socket")
conn_open_event.set()
CLIENT_WS = websocket
CONNECTION_OPEN = True
# send init message
await websocket.send(message)
while CONNECTION_OPEN:
await handleMessages(websocket, message)
await websocket.send(json.dumps({'type': MessageType.Close.name, 'message': USERNAME}))
await websocket.close()
async def main():
message = json.dumps({'payload':
'payload')
loop = asyncio.get_event_loop()
event = asyncio.Event()
start_light = asyncio.create_task(calculate_idle(3, event))
await asyncio.gather(init_connection(message, event), start_light)
asyncio.run(main())