首页 > 解决方案 > 当另一个函数在python上停止时如何停止一个函数

问题描述

我有一个工作功能,当用户写退出时停止,但我还有另一个功能不会停止,所以 cmd 只是保持打开状态,不会像它应该的那样关闭,因为其他功能不断改变 cmd 文本颜色

import os,webbrowser,time,random,sys
from threading import Thread 

def fun1():
    Q=1
    while Q==1:
        print ('would you like to:')
        print('1.launch an applcation')
        print('2.browse the internet')
        print('========================================')
        bruv=input('your answer: ')
        if bruv in ('1','launch','launch app','launch an application'):
            print('========================================')
            print('what app would you like to open?')
            print('========================================')
            x=input('your answer: ')
            if x not in ('word'):
                y=x+'.exe'
                os.startfile(y)
            else:
                z='win'+x
                os.startfile(z)
        if bruv in ('2','browse the internet','browse','browse internet'):
            print('========================================')
            print ('where would you like to go?')
            print('========================================')
            p=input('your answer: ')
            p='www.'+p+'.com'
            webbrowser.open(p)
            print('========================================')
            print ('ok')
        print('========================================')
        print ('wanna continue?')
        if input() in ('exit','no','quit','nope','close'):
            print('========================================')
            print ('ok! thanks for using my bot!')
            print('========================================')
            time.sleep(1)
            Q+=1
            countdown=3
            while countdown>=0:
                if countdown!=0:
                    print (countdown)
                    time.sleep(1)
                    countdown-=1
                else:
                    sys.exit()

def fun2():
    what=1
    while what==1:
        os.system('color E')
        time.sleep(0.2)
        os.system('color A')
        time.sleep(0.2)
        os.system('color C')
        time.sleep(0.2)
        os.system('color B')
        time.sleep(0.2)
        os.system('color D')
        time.sleep(0.2)
    else:
        sys.exit()

t1=Thread(target=fun1)
t2=Thread(target=fun2)

t1.start()
t2.start()

在这段代码中,fun2 不断滚动更改颜色并且不会关闭 CMD,我也知道这段代码非常糟糕,我刚刚开始使用 python。

标签: pythonmultithreadingpython-multithreading

解决方案


所以这里的问题是你的整个脚本(它启动你的两个函数/线程)默认只有在它启动的所有线程都停止时才会结束。所以你所有的函数都需要在某个时候返回,但你fun2()永远不会完成,因为无限循环while what==1总是会运行,what总是等于1. (作为旁注,Python 中无限循环的约定是使用while True: ...)。

要告诉 Thread 它应该在所有其他线程都完成时完成,您必须将其设为Daemon. 您可能想看这里,文档说:

可以将线程标记为“守护线程”。这个标志的意义在于,当只剩下守护线程时,整个 Python 程序就退出了。初始值继承自创建线程。该标志可以通过 daemon 属性或 daemon 构造函数参数设置。

因此,在您上面的示例中,制作t2一个守护程序应该可以工作。

... 
t1 = Thread(target=fun1)
t2 = Thread(target=fun2)
t2.deamon = True

t1.start()
t2.start()

PS:另请注意,color并非在所有终端和操作系统(例如 MacOS)中都有效


推荐阅读