[英]Python/Discord.py - How do I stop all running code but not stop the program?
I'm making a Discord bot with a lot of commands that take a while to finish (like loops) so I'd like to also have a command that stops any actively running code.我正在制作一个 Discord 机器人,其中包含许多需要一段时间才能完成的命令(如循环),因此我还希望有一个命令可以停止任何正在运行的代码。 I've tried sys.exit but I don't want to have to restart the program each time before it will take another input.我已经尝试过 sys.exit 但我不想每次都重新启动程序才能接受另一个输入。 Anyone know what I can do?有谁知道我能做什么?
It will depend on the way your code is formatted, but you will probably want to use functions that utilize boolean or return statements:这取决于您的代码格式,但您可能希望使用利用 boolean 或返回语句的函数:
def foo():
if end_this:
return
# stuff
If you have some tracking boolean end_this
that is set to True
, the function foo()
will not execute everything below.如果您有一些跟踪 boolean end_this
设置为True
,则 function foo()
将不会执行以下所有操作。 Alternatively, you could use a while-loop with a break in your code:或者,您可以在代码中使用带有中断的 while 循环:
def foo():
while True: # runs forever unless ended
# stuff
break
Now, foo()
will continue indefinitely until the break statement is reached.现在, foo()
将无限期地继续,直到到达 break 语句。 An if-statement can enclose the break, setting some logic on when the break occurs. if 语句可以包含中断,在中断发生时设置一些逻辑。 Again, this may require a main()
function to handle the calls and ends of your previous functions, but it would allow following code/functions to execute.同样,这可能需要main()
function 来处理先前函数的调用和结束,但它允许执行以下代码/函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.