Python 有没有办法打破它之外的循环(无错误)?
Python is there a way to break a loop outside of it (No Error)?
这是我的代码:
while i == 1:
mess = await message.channel.send("{:.2f}x".format(i))
i_adding = random.randint(1, 9) /100
i += i_adding
await asyncio.sleep(1)
while i < printing:
i_adding = random.randint(1, 9) /100
i += i_adding
await asyncio.sleep(1)
await mess.edit(content="{:.2f}x".format(i))
@client.command()
async def break(ctx):
await ctx.channel.send('Ok, now nothing should be send')
#break the "while i < printing"
我希望最后一行在“我 < 打印时”打破第二个循环
而且我不知道该怎么做!
如果你想这样做,你必须明确地这样做,例如共享一个 Event 对象,如果设置了 even 则退出循环。
一个可能的并发症是 threading.Event
is not async-aware and asyncio.Event
不是线程安全的,因此您可以拥有一个多线程系统,或者能够在等待 mess.edit
结果时“中断”。我不知道这两者是否重要,但你去吧。
最简单和最安全的方法是简单地检查循环中是否设置了 event
:
break_event = threading.Event()
...
while i == 1:
mess = await message.channel.send("{:.2f}x".format(i))
i_adding = random.randint(1, 9) /100
i += i_adding
await asyncio.sleep(1)
while i < printing and not break_event.is_set():
i_adding = random.randint(1, 9) /100
i += i_adding
await asyncio.sleep(1)
await mess.edit(content="{:.2f}x".format(i))
break_event.clear()
@client.command()
async def break(ctx):
await ctx.channel.send('Ok, now nothing should be send')
break_event.set()
这是我的代码:
while i == 1:
mess = await message.channel.send("{:.2f}x".format(i))
i_adding = random.randint(1, 9) /100
i += i_adding
await asyncio.sleep(1)
while i < printing:
i_adding = random.randint(1, 9) /100
i += i_adding
await asyncio.sleep(1)
await mess.edit(content="{:.2f}x".format(i))
@client.command()
async def break(ctx):
await ctx.channel.send('Ok, now nothing should be send')
#break the "while i < printing"
我希望最后一行在“我 < 打印时”打破第二个循环 而且我不知道该怎么做!
如果你想这样做,你必须明确地这样做,例如共享一个 Event 对象,如果设置了 even 则退出循环。
一个可能的并发症是 threading.Event
is not async-aware and asyncio.Event
不是线程安全的,因此您可以拥有一个多线程系统,或者能够在等待 mess.edit
结果时“中断”。我不知道这两者是否重要,但你去吧。
最简单和最安全的方法是简单地检查循环中是否设置了 event
:
break_event = threading.Event()
...
while i == 1:
mess = await message.channel.send("{:.2f}x".format(i))
i_adding = random.randint(1, 9) /100
i += i_adding
await asyncio.sleep(1)
while i < printing and not break_event.is_set():
i_adding = random.randint(1, 9) /100
i += i_adding
await asyncio.sleep(1)
await mess.edit(content="{:.2f}x".format(i))
break_event.clear()
@client.command()
async def break(ctx):
await ctx.channel.send('Ok, now nothing should be send')
break_event.set()