从python中的异步函数修改全局变量 [英] Modify global variable from async function in python

查看:181
本文介绍了从python中的异步函数修改全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用discord.py在Python中制作Discord机器人.我想从异步线程中设置/修改全局变量.

I'm making a Discord bot in Python using discord.py. I'd like to set/modify a global variable from an async thread.

message = ""

@bot.command()
async def test(ctx, msg):
    message = msg

但是,这不起作用.我该如何做到这一点?

However this doesn't work. How can I achieve something that does this?

推荐答案

正如我在评论中所说,无论您在何处修改全局变量,都必须在函数中使用关键字global.如果您只是在阅读功能,则不需要它.

As I said in the comment you have to use the keyword global in the functions wherever you are modifying the global variable. If you are just reading it in function than you don't need it.

message = ""

@bot.command()
async def test(ctx, msg):
    global message
    message = msg

这篇关于从python中的异步函数修改全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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