【问题标题】:In Discord.py, is it possible to wait for a variable to change from a different part of the code than the variable changes?在 Discord.py 中,是否可以等待变量从代码的不同部分更改而不是变量更改?
【发布时间】:2022-01-26 17:40:50
【问题描述】:

我尝试使用time.sleep(),但没有等待变量,而是暂停了整个代码,不允许变量更改。 这是我的代码:

@tasks.loop(seconds=5.0) #This is the code that changes the variable (Before this block of code, the variable fedex is defined)
  global check, fedex
  fedex = int(fedex) + r.randint(-500,500)
  if(check=="0"):
    check = "1"
  else:
    check = "0"

@client.command() #This is the code in which, after the variable changes, the bot should type if the variable fedex went up or down.
async def bet(ctx, arg1):
  def new():
    global current
    if(arg1=="fedex"):
      global fedex
      current = fedex
    else:
      return
  new()
  stok = current
  if(check=="0"):
    while(check != "1"):
      time.sleep(1.0)
  elif(check=="1"):
    while(check != "0"):
      time.sleep(1.0)
  new()
  stok2 = current
  if(stok2>stok):
    await ctx.send("It went up!")
  else:
    await ctx.send("It went down.")

我不知道用什么替换 time.sleep(1.0)

【问题讨论】:

    标签: python variables time discord.py sleep


    【解决方案1】:

    您可以改用await asyncio.sleep(1)Asyncio.sleep 的工作方式类似于 time.sleep,但它不会阻止整个代码执行。它只停止一个事件。同时,事件循环中的其他任务将继续运行。在使用time.sleep 时,您的整个代码不会做任何其他事情。但是,asyncio.sleep 要求事件循环在您的部分代码“休眠”时执行其他任务。

    Great explanation with examples

    【讨论】:

    • 非常感谢您的快速回复!这是 asyncio 和 time.sleep 之间的唯一区别,还是还有更多?另外,discord.py 中内置了 asyncio 还是我们必须导入它?
    • 它是异步编程中time.sleep 的替代品,这是一个非常广泛的主题,因此您可能需要阅读它以了解同步和异步编程之间的所有区别。这两者都在不同的情况下使用,但它们具有相似的目的 - 即停止您的代码。但是,asyncio.sleep 并非在所有情况下都有效。 Asyncio 是用 Python 构建的,您必须使用 import asyncio 导入它。
    • 好的,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    相关资源
    最近更新 更多