python - 当python中有一个循环时,我怎样才能让我的代码做其他事情
问题描述
我目前正在制作一个不和谐的机器人,我需要它在一些地方制作一些循环,但我还需要它准备好在循环中响应其他人。这是一个简化的示例:
n = 40
while n > 0:
print(n)
n -= 1
print('Hello')
在这里,我希望在循环发生时打印你好,而不是在它完成之后
解决方案
您需要使用 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())
随意尝试一下,看看它是如何工作的。
推荐阅读
- arrays - 如何在c中将char数组拆分为两种不同的类型?
- python-3.x - 在传递参数时使用 Python 读取文件
- geometry - Jira CircleCI 集成。请提供一个 CircleCI API 令牌以使该球体正常工作
- tinkerpop - 带有 spring-data-gremlin 的 Janusgraph
- reactjs - React 原生入职幻灯片
- python - qt.qpa.plugin:在“”中找不到 Qt 平台插件“windows”
- python - python中的FFT没有给出预期的结果
- elasticsearch - 使用 elasticsearch 注册的搜索模板不起作用
- swap - 什么理由?我有这样的错误“处理响应错误”
- r - 使用 MODISTools 时不断收到此错误