python - 退出函数不适用于线程方法
问题描述
我需要一些关于我以前在 python 中使用exit()
函数的代码的帮助,但今天我尝试使用线程库这是我的代码:
import time
import threading
ts = time.time()
ts_after = ts + 5
def printit():
global ts_after
threading.Timer(1.0, printit).start()
ts1 = time.time()
if int(ts1) >= int(ts_after):
print("11")
exit()
else:
pass
printit()
它工作得很好,print("11")
也可以工作,但exit()
打印后不起作用并继续打印 11
解决方案
在实例上使用该cancel()
方法Timer
似乎会产生您想要的行为:
import time
import threading
ts = time.time()
ts_after = ts + 5
def printit():
global ts_after
my_thread = threading.Timer(1.0, printit)
my_thread.start()
ts1 = time.time()
if int(ts1) >= int(ts_after):
print("11")
my_thread.cancel()
else:
pass
printit()
该cancel()
方法只是在实例开始之前停止Timer
它。请注意,扩展此代码以便它也可以退出Timer
已经启动的对象可能是一个好主意。
推荐阅读
- apache - 在 ubuntu 上部署 cakephp 应用程序时出错
- ruby-on-rails - 如何正确地将一个散列合并到另一个散列中,替换第一个键。回报率
- flutter - 在 Flutter SQFLite 数据库中监听实时变化
- python - 如何为 Spyder 安装 python 包
- java - SonarQube 不索引/查找 JAVA 文件
- c# - 通过 SDK 或 Interop 从 byte[] 打开 .doc 或 .xls
- javascript - VueJS中更新数据的机制?
- cassandra - 将数据迁移到新集群后,Cassandra 集群中的数据不一致
- amazon-web-services - AWS CLI 将输出加载到多行
- android - 无法使用辅助功能服务检测来自其他应用程序窗口的文本