python - 当另一个函数在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。
解决方案
所以这里的问题是你的整个脚本(它启动你的两个函数/线程)默认只有在它启动的所有线程都停止时才会结束。所以你所有的函数都需要在某个时候返回,但你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)中都有效
推荐阅读
- google-sheets - 谷歌表格 - 设置范围直到列的末尾并将每列设置为 3 列的总和
- java - Android 错误 java.lang.OutOfMemory:分配失败
- mysql - 无法通过工作台连接到mysql db,但可以通过终端登录
- r - 从字符向量列表中选择公共项
- r - 在子列表列表中搜索项目,并获取包含该项目的子列表的名称
- cordova - Ionic4/Cordova - 服务无法启动,要么是因为它被禁用,要么是因为它没有与之关联的启用设备
- python - 关于python系统打印结果的问题
- python - 如何检查字符串列表是否同名?
- scanning - 如何在我的 nixos 主机上为 HP OfficeJet Pro 设置简单扫描
- firebase - 我得到了这个错误并且无法解决它:反序列化时期望一个列表,但得到一个类 java.lang.String;