当我调用 stop()
时,我不明白为什么线程对象 threadObj
不能使用 isAlive
。代码说明如下。
from threading import Thread
class workerThread(Thread):
def __init__(self, _parent):
Thread.__init__(self)
self.parent = _parent
self.active = False
def run(self):
while(self.active == False):
print 'I am here'
print 'and now I am here'
class imp():
def __init__(self):
self.threadObj = None
def start(self):
self.threadObj = workerThread(self)
self.threadObj.start()
def stop(self):
if self.threadObj.isAlive() == True:
print 'it is alive'
它说:AttributeError:“NoneType”对象没有属性“isAlive”
调用代码如下:
from filename import imp
filename = imp()
if option == 'A':
filename.start()
elif option == 'B':
filename.stop()
最佳答案
您的问题似乎是您错误地认为您的线程在程序调用之间是持久的,这是不正确的。当您调用 python CallingCode.py A
时,您的程序将运行并执行 if option == 'A'
代码块。然后它退出,并且你的线程被清理。第二次,当您调用 python CallingCode.py B
时,永远不会创建线程。
关于python - 线程对象问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23836211/