【问题标题】: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')