python - 如何获取在类内运行的任务的当前状态
问题描述
我有一个做很多事情的类,在那个类中我有一个需要一些时间才能完成的函数。获取该功能当前正在执行的“状态”的最佳方法是什么?线程是一个解决方案还是我应该启动一个进程或其他什么?
我正在尝试做的事情:
import threading
import time
class Work:
def __init__(self):
self.status = "created"
def get_status(self):
return self.status
def slowFunction(self):
self.status = "slowFunction started working"
time.sleep(300)
self.status = "did some work"
time.sleep(300)
self.status = "slowFunction finished"
#a lot more things here
#...
if __name__ == "__main__":
obj = Work()
t = threading.Thread(target=obj.slowFunction())
t.start()
while obj.get_status() != "slowFunction finished"
print obj.get_status()
time.sleep(5)
我希望循环在启动线程后立即启动,它目前正在等待 slowFunction 完成。
解决方案
slowFunction
作为线程目标传递时删除括号。
t = threading.Thread(target=obj.slowFunction)
推荐阅读
- postgresql - 是否可以使用外部库来扩展云 sql postgres 的功能?
- node.js - 连接超时后节点http客户端重新连接
- python - 如何在基于 loc 条件更新一系列行的同时迭代 Pandas 行?
- swift - 使用 ARKit 可视化表面上的放置点
- python - Pandas:对于特定列中的所有重复条目集,获取一些信息
- windows - 使用“dotnet dev-certs https”创建的证书的默认位置是什么
- javascript - Javascript 正则表达式最小长度匹配
- google-maps - 如何在缩小下使管理.land_parcel 几何可见
- oracle-apex-5.1 - Oracle APEX - 文本字段显示破折号
- python - 没有 in 的 python 列表理解