【问题标题】:How can I let my code do other stuff while there is a loop going on in python当python中有一个循环时,我怎样才能让我的代码做其他事情
【发布时间】:2021-07-08 22:22:48
【问题描述】:

我目前正在制作一个不和谐的机器人,我需要它在某些地方制作一些循环,但我还需要它准备好在循环中响应其他人。 这是一个简化的示例:

n = 40
while n > 0:
  print(n)
  n -= 1
print('Hello')

这里我希望在循环发生时打印你好,而不是在它完成之后

【问题讨论】:

标签: python loops discord discord.py


【解决方案1】:

你需要使用Asyncio https://docs.python.org/3/library/asyncio.html

这是一个在“相同”时间打印奇数和偶数的示例。

import asyncio, time

#prints out even numbers
async def func1():
    evenNumbers = [num for num in range(50) if num % 2==0]
    for num in evenNumbers:
        await asyncio.sleep(1)
        print(num)

#prints out odd numbers
async def func2():
    oddNumbers = [num for num in range(50) if num % 2!=0]
    for num in oddNumbers:
        await asyncio.sleep(1)
        print(num)

#handles asynchronous method calling
async def main():
    await asyncio.gather(
        func1(),
        func2()
    )

asyncio.run(main())

随意尝试一下,看看它是如何工作的。

【讨论】:

    【解决方案2】:

    我不确定 discord bot,但总的来说,您可以使用线程同时执行多项操作。

    例如:

    import threading
    
    def thread_function():
        n = 40
        while n > 0:
            print(n)
            n -= 1
    
    th = threading.Thread(target=thread_function)
    th.start()
    
    print('Hello')
    

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2011-09-22
      • 2021-12-20
      • 2021-06-11
      • 2012-10-04
      相关资源
      最近更新 更多